Curriculum
Course: React
Login

Curriculum

React

Text lesson

Props

Components can be passed as props, short for properties. Props function like arguments in a function and are sent to the component as attributes. You will learn more about props in the next chapter.

Example

Pass a color to the Car component using an attribute, and utilize it within the render() function.

 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 in Components

Components can be used within other components.

Example

Embed the Car component within the Garage component.

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 Files

React emphasizes code reuse, so it’s advisable to split your components into separate files. To achieve this, create a new file with a .js extension and place the component code inside it.

Ensure that the filename starts with an uppercase character.

Example

This is the new file, named “Car.js”.

function Car() {
 return <h2>Hi, I am a Car!</h2>;
}

export default Car;

To use the Car component, you need to import the file into your application.

Example

Now that we’ve imported the “Car.js” file into the application, we can use the Car component as if it were created directly in this file.

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 />);