This is my code:
Why is this not working?
The code is suppose to show the h1 in the html file, but for some reason it doesn't do that for me.
Element.js :
import React from "react"
function Element() {
return (
<div>
<h1>Hello World</h1>
</div>
)
}
export default Element
app.js :
import React from 'react'
import ReactDOM from 'react-dom'
import Element from './Element.js'
ReactDOM.render(<Element />, document.getElementById('root'))
the html code:
<script src="/index.js" type="text/babel"></script>
<div id="root"></div>
I looked at many solutions at stackoverflow but this bug it still doesn't work. I added import React from "react" and import ReactDOM from "react-dom" in both files but still same thing: nothing in the return statement doesn't show up, I've been struggling for hours. What is wrong with my code?
Following things need to improve into your code-
1-Use of root level rendering things in index.js instead of app.js.
index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App.js";
ReactDOM.render(
<App /> ,
document.getElementById("root")
);
2-Use App.js file to accumulate all other component into it.
App.js
import Element from './Element'
function App() {
return (
<div className='App'>
<Element />
</div>
)
}
PS: Learn the heirarchy of react and its flow . This links may be helpful:
React Rendering - https://reactjs.org/docs/rendering-elements.html
Introduction to react rendering https://medium.com/information-and-technology/an-introduction-to-react-rendering-9c24a96b838b
It appears that there are three issues here. With the code provided, thats what I get.
type attribute needs a change. You can completely remove it too.render method. You have to fitst create a root, and then render the app like soconst root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Element />);
root div element, coz the script when gets executed may not know the element with id root.I would re-do the app.js to
import Element from './test'
function App() {
return (
<div className='App'>
<Element />
</div>
)
}
export default App
PS. also some links to the official documentation and how to use react https://reactjs.org/docs/create-a-new-react-app.html https://reactjs.org/docs/rendering-elements.html
PS 2: or if You would really like to do it in the old way
import React from 'react'
import './App.css'
import Element from './test'
function App() {
return React.createElement('div', {}, React.createElement(Element))
}
export default App