Loading lesson path
Components are like functions that return HTML elements.Components are independent and reusable bits of code.
They serve the same purpose as JavaScript functions, but work in isolation and return HTML.Components come in two types, Class components and Function components, in this tutorial we will concentrate on Function components. In older React code bases, you may find Class components primarily used. It is now suggested to use Function components along with Hooks, instead of Class components. Class components are still supported, check the Class components section for more information.
When creating a React component, the component's name
start with an upper case letter. React components returns HTML code.
Car function Car() {
return (Formula
< h2 > Hi, I am a Car!</h2 >);
}Now your React application has a component called Car, which returns an <h2> element. To use this component in your application, refer to it like this: <Car />
Car component in the "root" element: createRoot(document.getElementById('root')).render( <Car /> )
Example »
Arguments can be passed into a component as props, which stands for properties. You send the arguments into the component as HTML attributes. You will learn more about props in our React Props chapter.
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>
);
}createRoot(document.getElementById('root')).render( <Car color="red"/>
);Example »
We can refer to components inside other components:
function Car() {
return (Formula
< h2 > I am a Car!</h2 >);
}function Garage() {
return (<>
Formula
< h1 > Who lives in my Garage?</h1 ><Car /> </>
);
}createRoot(document.getElementById('root')).render( <Garage />
);Example »
We can render a component multiple times:
function Car() {
return (Formula
< h2 > I am a Car!</h2 >);
}function Garage() {
return (<>
Formula
< h1 > Who lives in my Garage?</h1 ><Car /> <Car /> </>
);
}createRoot(document.getElementById('root')).render( <Garage />
);