Props is an object that is passed down to components as arguments.props
is the object used to pass data from parent to child component.
Props are passed down to elements via custom attributes in the component.
Below are examples of two component, a Header
and a Title
. Title
is nested inside the Header
and it’s passed a prop
called title
.
The text of the title is saved in a const
inside the Header
component and passed down to Title
component as a prop
named title
.
Inside Title
component we access the title text through props.title
is the object that contains all the props and
propsprops.title
returns the value of the title.
const Header = () => {
const title = "This is my title passed as a prop";
return(
<div className="header">
<Title title={title} />
</div>
)
}
const Title = props => {
return (
<h1>{props.title}</h1>
)
}
Rendering multiple elements in an array
JSX
can render components when they are passed to it into an array. We use Array.map()
to pass props for multiple elements in an array.
Here’s an example of a TodoList
that passes props to a Todo
element
const TodoList = props => {
return(
<div>
{props.todos.map(todo => {
return(
<Todo
todo={todo}
task={todo.task}
key={todo.id}
/>
)
})}
</div>
)
}
Whatever we return in the map function is added to a new array.
In this case we are returning Todo
components with props that are added to the new array created by Array.map
then renders the new array as a list of components.
JSX
Do you like these posts? You can receive them directly in your inbox.
Just enter your email below to subscribe to this newsletter. I promise there will be no spam, only engaging content. And you can unsubscribe at any time.