I am absolute beginner in react. I have to pass particular property to all the components inside the div without passing them into individual, For Example, Instead of doing this:
function App() {
return (
<div>
<Component1 props = {propObject}/>
<Component2 props = {propObject}/>
<Component3 props = {propObject}/>
</div>
);
}
How can I achieve something like this? :
function App() {
return (
<div props={propObject}>
<Component1 />
<Component2 />
<Component3 />
</div>
);
}
CodePudding user response:
React Context
provides a way to share values to child components without having to explicitly pass a prop through every level of the tree.
You need to import React.context
from react
syntax:
// context.js
import React, { createContext } from "react"
export const MyContext = React.createContext(null);
Now You need to create a provider of this context, to pass the current context value to the tree below. So you need to wrap all of your child component
by the React.Provider
.
syntax:
// MainComponent.js
import { MyContext } from "./context"
import { ChildComponent1, ChildComponent2, ChildComponent3 } from "./childcomponent"
const MainComponent = () => {
const myObject = {name: "John"}
return (
<MyContext.Provider props={myObject}>
<ChildComponent1 />
<ChildComponent2 />
<ChildComponent3 />
</MyContext.Provider>
)
}
Now all the child component of this MainComponent
has access of this props
value which is provided by MyContext.Provider
. Now you can simply get that values to your child components.
syntax:
// childcomponent.js
import React, { useContext } from "react"
import { MyContext } from "./context"
export const ChilcComponent1 = () => {
const props = useContext(MyContext)
return (
<p>
My name is: {props?.key}
</p>
)
}
CodePudding user response:
You can use from ThemeProvider:
function App() {
return (
<ThemeProvider props = {propObject}>
<Component1 />
<Component2 />
<Component3 />
</ThemeProvider >
);
}