React components let you break up the user interface into separate pieces that can then be reused and handled independently.
A React component takes an optional input and returns a React element which is rendered on the screen.
A React component can be either “stateful” or “stateless.”
“Stateful” components are of the class type, while “stateless” components are of the function type.
An example of how this might be executed follows below:
import React from 'react'; require('./style.css'); import ReactDOM from 'react-dom'; import App from './app.js'; ReactDOM.render( <App />, document.getElementById('root') );
The above example shows a stateless component named ExampleComponent
which is inserted in the <App/>
component. The ExampleComponent
just comprises of a <h1>
element.
An example of how this might be executed is provided below:
import React from 'react'; require('./style.css'); import ReactDOM from 'react-dom'; import App from './app.js'; ReactDOM.render( <App />, document.getElementById('root') );
The above example shows a stateful component named ExampleComponent
which is inserted in the <App/>
component. The ExampleComponent
contains a <h1>
and the <h2>
element wrapped in a <div>
. The <h1>
displays data using props while the <h2>
takes its data from the internal state of the ExampleComponent
.
Props are an optional input, and can be used to send data to the component. They are immutable properties, which makes them read-only. This also makes them come in handy when you want to display fixed values.
A React component of class type maintains an internal state which acts as a data store for it. This state can be updated and whenever it is changed, React re-renders that component.
Every component has “lifecycle methods”. They specify the behavior of the component when it undergoes a phase of its lifecycle.
Some examples of different phases could be: when the component is just about to render on the screen, when it has rendered on the screen, or when it is updated/modified in response to a request.
For example, componentWillMount
is executed just before the React Component is about to mount on the DOM and componentDidMount
executes after the component mounts on the DOM.
Free Resources