Components are core building blocks for applications developed by React. They return React elements written in JSX. Components are stateful and help you to build dynamic & interactive UI screens.
React follows Component-driven development which means entire view is divided into components. Each component is specifically designed to do only one particular task. So all the logic required for the task is encapsulated into one component. This makes maintenance and debugging very easy.
Each component will have everything needed for displaying view like state(data), logic, event handlers (for example: button clicks, form input changes) and styles.
React
var container1 = document.getElementById('container-1');
Basic Component Example
function FirstComponent() {
return <h4>First Example of Component !!</h4>
}
ReactDOM.render(<FirstComponent />, container1);
Let's breakdown example step by step.
- We created a function which returns a JSX statement.
- ReactDOM.render was called with element
. Function is rendered as element, these kind of functions are called Functional Components, React will understand make them available as elements.
Transpiled version of above code.
function FirstComponent() {
return <p>First Example of Component !!</p>
}
ReactDOM.render(<FirstComponent />, container1);
Component using React Class
var container2 = document.getElementById('container-2');
class TestComponent extends React.Component {
render() {
return (<h4> Example using React Class </h4>);
}
}
ReactDOM.render(<TestComponent />, container2);
Let's breakdown example step by step.
- We created a class which extends render method returned
- render method returned a JSX statement. This method is mandatory while creating Components using classes. Only element within render method is attached to DOM.
- ReactDOM.render was called with element
.
Transpiled version of above code.
class TestComponent extends React.Component {
render() {
return (<h4> Example using React Class </h4>);
}
}
ReactDOM.render(<TestComponent />, container2);