Skip to content

JSX components in React

Components are the building blocks of a React application.

A component is a reusable piece of code that describes how a part of the user interface (UI) should look and behave.

Components can be nested inside other components to create complex user interfaces.

In React, it is best to create components using functions. These are called, unsurprisingly enough, “functional components”.

Here’s an example of a simple functional component:

function Greeting() {
return <h1>Hello</h1>
}

When this component is rendered, it will display a <h1> element with the text “Hello”.

You can render this component in another component like this:

function Greeting() {
return <h1>Hello</h1>
}
function ProfileRoute() {
return (
<div>
<Greeting />
</div>
)
}

When ProfileRoute is rendered, it will display a <div> element containing the <Greeting> component.

Better still, you can define your components in completely separate files and import them into the file where you want to use them.

Here’s an example of how you can do this:

function Greeting() {
return <h1>Hello</h1>
}
export default Greeting;

Components can also render images. Here’s an example of a component that renders an image:

function Avatar() {
return <img src="https://via.placeholder.com/150" alt="Avatar" />
}

When this component is rendered, it will display an <img> element with the specified src and alt attributes.

This image takes as its source a URL from placeholder.com. This is a service that provides placeholder images for use in web development.

However, most of the time you would want to import images from your project’s assets folder.

You can do this by importing the image, storing its path as a variable, then finally using it as the src attribute of the <img> element.

If we take the same example as above, but with an image imported from the assets folder:

import avatar from './assets/avatar.png'
function Avatar() {
return <img src={avatar} alt="Avatar" />
}

Watch the video below to see how I solved the challenges:

Once you have your component set up, you can move on to the next section.