What are React Components?
React components are like functions that return HTML elements. They allow you to break your UI into independent, reusable parts, which can be developed and managed separately.
Components can be broadly classified into two types:
- Class Components (used in older React codebases).
- Function Components (modern React applications prefer these, especially with the introduction of Hooks).
Creating Your First React Component
When creating a component, its name must start with an uppercase letter to follow React’s conventions.
Class Components #
Class components are defined using the class
keyword and extend React.Component
. They include a render()
method that returns the HTML to be displayed.
class Car extends React.Component {
render() {
return <h2>Hi, I am a Car!</h2>;
}
}
Function Components #
Function components are simpler to write and are preferred in modern React applications. They return HTML directly from a JavaScript function.
function Car() {
return <h2>Hi, I am a Car!</h2>;
}
Rendering a Component #
To display a React component, you can use the render()
method of the ReactDOM.createRoot()
function.
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Car />);
Props (Properties) #
Props are used to pass data to components, making them dynamic and reusable. These are similar to function arguments.
Example of passing a color
prop to the Car
component:
function Car(props) {
return <h2>I am a {props.color} Car!</h2>;
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Car color="red" />);
Components within Components #
React allows you to nest components inside other components.
function Car() {
return <h2>I am a Car!</h2>;
}
function Garage() {
return (
<>
<h1>Who lives in my Garage?</h1>
<Car />
</>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage />);
Components in Separate Files #
For better reusability, it’s common to define each component in a separate file. For example:
Car.js
function Car() {
return <h2>Hi, I am a Car!</h2>;
}
export default Car;
To use this Car
component, import it into another file and render it:
import React from 'react';
import ReactDOM from 'react-dom/client';
import Car from './Car.js';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Car />);
Want to learn React with an instructor, either offline or online? Find experienced tutors near you and join Coaching Wallah—completely free for students!
Leave your comment