This blog describes how to create a React component that takes a name prop and displays a greeting message.
You can create a React component that takes a name
prop and displays a greeting message by simply using that prop within the component. Here’s how you can do it.
Greeting.js
import React from 'react';
const Greeting = ({ name }) => {
return (
<div>
<h1>Hello, {name}!</h1>
</div>
);
};
export default Greeting;
App.js
import React from 'react';
import Greeting from './Greeting';
const App = () => {
return (
<div>
<Greeting name="Alice" />
<Greeting name="Bob" />
</div>
);
};
export default App;
In this example:
- We define a functional component called
Greeting
. - We destructure the
name
prop from the props object passed to the component. - Inside the component’s return statement, we use the
name
prop to dynamically generate the greeting message. - We render the greeting message inside an
<h1>
element.
Now, you can use this Greeting
component and pass the name
prop to it wherever you need to display a greeting message.
In this example, Greeting
component is used twice, with different name
props (“Alice” and “Bob”). Each instance of the Greeting
component will display a greeting message with the corresponding name.
Output
Further Reading
Spring Framework Practice Problems and Their Solutions
From Google to the World: The Story of Go Programming Language
Why Go? Understanding the Advantages of this Emerging Language
Creating and Executing Simple Programs in Go
20+ Interview Questions on Go Programming Language