-- Main.shssdhakchina - 01 Feb 2022
Functional Components
Functional components are very easy to create and was intended to act as a stateless components development. Suppose you want to display some information only on a particular part of the web application, then functional components are very much preferred to quickly finish the job.
Creating a simple component
Create a Function component called
Car
function Car() {
return <h2>Hi, I am a Car!</h2>;
}
Rendering a Component
Now your React application has a component called Car, which returns an <h2> element.
To use this component in your application, use similar syntax as normal HTML: <Car />
Example
Display the Car component in the "root" element:
ReactDOM.render(<Car />, document.getElementById('root'));
Props
Components can be passed as props, which stands for properties.
Props are like function arguments, and you send them into the component as attributes.
You will learn more about props in the next chapter.
Example
Use an attribute to pass a color to the Car component, and use it in the render() function:
function Car(props) {
return <h2>I am a {props.color} Car!</h2>;
}
ReactDOM.render(<Car color="red"/>, document.getElementById('root'));
Components in Components
We can refer to components inside other components:
Example
Use the Car component inside the Garage component:
function Car() {
return <h2>I am a Car!</h2>;
}
function Garage() {
return (
<>
<h1>Who lives in my Garage?</h1>
<Car />
</>
);
}
ReactDOM.render(<Garage />, document.getElementById('root'));
Components in Files
React is all about re-using code, and it is recommended to split your components into separate files.
To do that, create a new file with a .js file extension and put the code inside it:
Note that the filename must start with an uppercase character.
Example
This is the new file, we named it "Car.js":
function Car() {
return <h2>Hi, I am a Car!</h2>;
}
export default Car;
To be able to use the Car component, you have to import the file in your application.
Example
Now we import the "Car.js" file in the application, and we can use the Car component as if it was created here.
import React from 'react';
import ReactDOM from 'react-dom';
import Car from './Car.js';
ReactDOM.render(<Car />, document.getElementById('root'));