A react component is small chunk of user interface which will be render on webpage. The component update whenever its internal state is changed, it also allows to interact using events specified in the component. Each react component has their own life cycle methods throw which it has to gone through and perform operation.
Ways to create component in ReactJs
1. | Function component − Uses plain JavaScript function |
2. | ES6 class component − Uses ES6 class |
Function component − Uses plain JavaScript function
The ReactJs allows to create component by using javascript function which returns a React element. The functional component is very minimal in nature.
1 import React from 'react';
2
3 function Hello() {
4 return <div>Hello welcome to React function component !! </div>;
5 }
6 export default Hello;
In the above example, a functional component created with export and default keyword before function keyword, it creates new component and export as default. A default keyword specifies when file imported in other component, a component imported as default. A component can be exported by specifying a name with export keyword at the end of component.
ES6 class component − Uses ES6 class
The ReactJs allows to create component by using ES6 class syntax which will returns a single React element. Class components supports state management out of the box and provide life cycle method.
1 import React from 'react';
2
3 class Hello extends React.Component {
4 render() {
5 return <div>Hello welcome to React class component !! </div>;
6 }
7 }
8 export default Hello;
In the above example, a class component Hello is created by extending a React.Component with render() method. A render() method must return a single element or a wrapper element. A component is exported as default which can be import and added to the parent component. It replace an element and renders a specified div element that returned from render() method.
Import and use class component
Import and use class component
1 import React from 'react';
2 import './style.css';
3 import Hello from './components/hello';
4
5 function App() {
6 return (
7 <div className="App">
8 <h3>React main component </h3>
9 <Hello /> {}
10 </div>
11 );
12 }
13
14 export default App;
In the above example, a function component is imported using import statement, it imports component which is define with default keyword. A component is imported and added into the parent component as element. When an App component render on browser, it renders class component inside App component.
1 .App {
2 margin: 10px;
3 border: 1px solid blue;
4 padding: 10px;
5 border-radius: 5px;
6 }
Related options for your search