Rendering an Element into the DOM (ReactDom)
Let’s say there is a < div > somewhere in your HTML file:
<div id="root"></div>
We call this a “root” DOM node because everything inside it will be managed by React DOM.
const element = <h1>Hello, world</h1>
const node = document.getElementById('root')
ReactDOM.createRoot(node);
React Element
A Simple Component
React components extends React.Component.
class HelloWorld extends React.Component {
render() {
return (
<div>Hello World</div>
)
}
}
const node = document.getElementById('root')
const root = ReactDOM.createRoot(node);
root.render(<HelloWorld />);
A Simple function
A stateless component can be replace by a simple function.
const HelloWorld = () => {
return (
<div>Hello World</div>
);
}
const node = document.getElementById('root')
const root = ReactDOM.createRoot(node);
root.render(<HelloWorld />);
Props
Input data that is passed into the component can be accessed via this.props in a React Component or in the parameters in a simple function.
class HelloMessage extends React.Component {
render() {
return (
<div>Hello {this.props.msg}</div>
)
}
}
const node = document.getElementById('root')
const root = ReactDOM.createRoot(node);
root.render(<HelloWorld />);
const HelloMessage = (props) => (
<div>Hello {props.msg}</div>
)
State
Every component can have an internal state.
Initialize
You have to initialize your state in the constructor. When we override the constructor, you have to pass the props to the parents.
constructor(props) {
super(props);
this.state = {firstName: 'John', lastName: 'Doe', age: 20};
}
Modify
To modify the state you have to use the this.setState function. Only the specific change will affect.
this.setState({firstName: 'Johnny'})
If you have to use precedent state, you should give to setState a function.
this.setState((state) => ({ age: state.age + 1 })