React is, in short, nothing but creating UI components. Let’s see how we can create components in React.
1. What is Component?
A React Component is, in short, a JavaScript function that generates an output every time it is invoked. You can directly return UI through a function or wrap the function (render()) inside a class.
- A component is responsible to render the UI content
- A component can be nested inside other components
2. Virtual DOM
A virtual DOM is an in-memory representation of real DOM. React uses the virtual DOM to minimize changes to the real DOM as a result of user actions. Through Virtual DOM diffing, React only updates what has been modified. This process is called as “Tree reconciliation“.
3. Function Component
A function (presentational) component
- handles props (read-only data)
- cannot have state
import React from 'react'; const Greet = (props) => { return ( <div>Hello, {props.name}</div> ); }; export default Greet;
You need to use a function component whenever possible. It is simpler than the class counterpart. If you do not need to change the state, stick to the function component.
4. Class Component
A React class component
- inherits from React.Component base class
- returns UI in the render() method
- can have props and states
import React from 'react'; class Greet extends React.Component { render() { return ( <div>Hello, {this.props.name}</div> ); } } export default Greet;
Class component can have states as well as props. When states are changed, the class component is re-rendered automatically.
5. How to use components
It is easy to use the components in other components.
- Import the Component
- In the render() function, refer the component like a tag
- You can pass the props like attributes
import React from 'react'; import Greet from './Greet'; function TestPage(props) { return ( <div><Greet name="World1" /></div> ); } export default TestPage;
6. Referencing the Main Component – Main Renderer
So you can wrap all your components in a root (main) component. Now, it is time to reference the main component in a html.
At first create a html with the root div.
<div id="app"></div> <script src="/bundle.js"></script>
In the main JavaScript file,
- Import the “react-dom” package
- Call the react-dom‘s render() method with the root component
- Pass the html root element in the render()
import ReactDOM from 'react-dom'; ReactDOM.render(<App />, document.getElementById('app') );