JSX components in React
What are React components?
Section titled “What are React components?”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”.
Embedding components
Section titled “Embedding components”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.
Importing components from other files
Section titled “Importing components from other files”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;
import Greeting from './Greeting';
function ProfileRoute() {return ( <div> <Greeting /> </div>)};
Rendering images
Section titled “Rendering images”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.
Importing images
Section titled “Importing images”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" />}
Challenges
Section titled “Challenges”Solution
Section titled “Solution”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.