☰ See All Chapters |
ReactJS Components
Everything in reactjs is components. The core building blocks of React application is components only. Components interact with each other and maintain the state too. In Reactjs whole application is need to be break into the component only. Components are independent and reusable bits of code. Components come in two types:
Class components
Function components
Class Component
When a class extends React.Component class it becomes component. This component class should extend render() function and should return JSX from this function. Class name will be the component name.
import React from 'react';
class HelloComponent extends React.Component { render() { return <h1>Hello World!</h1>; } } export default HelloComponent; |
Function Component
Components can be created using function with much less code. Function has to return JSX and function name will be the component name.
function HelloComponent() { return ( <h1> My First Component</h1> ); }
export default HelloComponent; |
Components inside Components
We can refer to components inside other components:
childcomponent.js
function ChildComponent() { return ( <h1> Hello World from child component</h1> ) }
export default ChildComponent; |
parentcomponent.js
import ChildComponent from './chilcomponent.js';
function ParentComponent() { return ( <div> <ChildComponent></ChildComponent> <h1>Hello World from first component</h1> </div> ) }
export default ParentComponent; |
index.js
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import ParentComponent from './components/parentcomponent'; import reportWebVitals from './reportWebVitals';
ReactDOM.render( <React.StrictMode> <ParentComponent></ParentComponent> </React.StrictMode>, document.getElementById('root') );
reportWebVitals(); |
All Chapters