In the previous blog post, we learned how to render a simple component in React using JSX. In this blog post, we will learn how to pass data to a component using props and display it in the component.
Step 1: Create a new file
Create a new file called Person.js
in the src
folder of your React project.
Step 2: Write the component code
In the Person.js
file, write the following code:
import React from 'react';
const Person = (props) => {
return (
<div>
<h1>{props.name}</h1>
<p>{props.age} years old</p>
</div>
);
}
export default Person;
Here, we have created a functional component called Person
which accepts props
as an argument. Inside the component, we have used the props
object to display the name
and age
of the person.
Step 3: Render the component
In the App.js
file, modify the code as follows:
import React from 'react';
import Person from './Person';
function App() {
return (
<div>
<h1>My React App</h1>
<Person name="John Doe" age="25" />
</div>
);
}
export default App;
Here, we have imported the Person
component and used it inside the App
component by passing name
and age
as props.
Step 4: Run the application
Save the files and start the React application using the following command in the terminal:
npm start
Visit localhost:3000 in your browser to see the output.
In the browser, you should see the following:
Congratulations! You have successfully passed data to a component using props and displayed it in the component.