How do you pass data to React components?
There are 2 main ways of passing data to React components:
- Props
- Context API Props are data passed from a component's immediate parent. Props are declared on the child component, can be named anything, and can accept any valid value.
function Blog() {
const post = { title: "My Blog Post!" };
return <BlogPost post={post} />;
}
Props are consumed within the child component. Props are always available within the child as properties on an object.
function BlogPost(props) {
return <h1>{props.post.title}</h1>
}
Since props are plain object properties, they can be destructured for more immediate access.
function BlogPost({ post }) {
return <h1>{post.title}</h1>
}
Context is data passed from a context provider to any component that consumes the context.
Context allows us to access data anywhere in our app (if the provider is passed around the entire component tree), without using props.
Context data is passed down on the value
prop using the Context.Provider
component. It can be consumed using the Context.Consumer component or the useContext
hook.
import { createContext, useContext } from 'react';
const PostContext = createContext()
function App() {
const post = { title: "My Blog Post!" };
return (
<PostContext.Provider value={post}>
<Blog />
</PostContext.Provider>
);
}
function Blog() {
return <BlogPost />
}
function BlogPost() {
const post = useContext(PostContext)
return <h1>{post.title}</h1>
}