If you are consistently asking yourself how to pass props to a component in React here is an explanation for passing props to class and functional components.
In React, props stand for "properties" and they are the way we pass data from one React component to another. Props are passed as arguments into a React component. The syntax for passing props is the same for class and functional components, but the syntax for accessing these props is different.
To pass props to a class component you define the name of the prop and then pass a value inside curly brackets.
To access the props you will use the this
keyword to access the props
object which contains the props you passed into the component.
class App extends Component {
render() {
const blogPost = {
title: 'How to pass prop to components',
description: 'Your component library for ...',
};
return (
<div>
<BlogCard title={blogPost.title} description={blogPost.description} />
</div>
);
}
}
class BlogCard extends Component {
render() {
return (
<div>
<h1>{this.props.title}</h1>
<p>{this.props.description}</p>
</div>
);
}
}
For a functional component, you will pass props the same way as class components, define the name of the prop and then pass a value inside curly brackets.
Where class and functional components differ is in accessing props. In a functional component, you will see the props object as a parameter and can access it without the this
keyword. It is also best practice to destructure
the object using the destructuring assignment syntax
to make it clear what props you are expecting in the component.
function App() {
const blogPost = {
title: 'How to pass prop to components',
description: 'Your component library for ...',
};
return (
<div>
<BlogCard title={blogPost.title} description={blogPost.description} />
</div>
);
}
function BlogCard({ title, description }) {
return (
<div>
<h1>{title}</h1>
<p>{description}</p>
</div>
);
}
Since Javascript is not a typed language there is a helpful package to validate the prop types passed into a React component, which will help when reading and debugging code.
This package is called prop-types.
Here is an example of using prop-types to validate our props.
import PropTypes from 'prop-types';
function BlogCard({ title, description }) {
return (
<div>
<h1>{title}</h1>
<p>{description}</p>
</div>
);
}
BlogCard.propTypes = {
title: PropTypes.string,
description: PropTypes.string,
};