score:3
1. setting parent state for dynamic context
firstly, in order to have a dynamic context which can be passed to the consumers, i'll use the parent's state. this ensures that i've a single source of truth going forth. for example, my parent app will look like this:
const app = () => {
const [name, setname] = usestate("john");
const value = { name, setname };
return (
...
);
};
the name is stored in the state. we will pass both name and the setter function setname via context later.
2. creating a context
next, i created a name context like this:
// set the defaults
const namecontext = react.createcontext({
name: "john",
setname: () => {}
});
here i'm setting the defaults for name ('john') and a setname function which will be sent by the context provider to the consumer(s). these are only defaults and i'll provide their values when using the provider component in the parent app.
3. creating a context consumer
in order to have the name switcher set the name and also showing, it should have the access to the name setter function via context. it can look something like this:
const nameswitcher = () => {
const { name, setname } = usecontext(namecontext);
return (
<label>your name:</label><br />
<input type='text' onchange={e => setname(e.target.value)} />
<p>{name}</p>
);
};
here i'm just setting the name to input value but you may have your own logic to set name for this.
4. wrapping the consumer in a provider
now i'll render my name switcher component in a namecontext.provider and pass in the values which have to be sent via context to any level deeper. here's how my parent app look like:
const app = () => {
const [name, setname] = usestate("john");
const value = { name, setname };
return (
<name.provider value={value}>
<nameswitcher />
</name.provider>
);
};
score:2
you need to export your usercontext, so it can be imported in the components that need it:
export const usercontext = react.createcontext();
function app() {
const [name, setname] = usestate('name');
return (
<usercontext.provider value={{ name, setname }}>
<home />
</usercontext.provider>
);
}
afterwards you can import it in your app component:
import { usercontext } '../../app'
function home() {
const user = usecontext(usercontext);
return (
<>
<label>your name:</label>
<input type='text' onchange={e => user.setname(e.target.value)} />
<p>{user.name}</p>
</>
)
}
Source: stackoverflow.com
Related Query
- How do I pass a React Context's state through an onClick function created in a method inside that context class?
- How to pass State in Context React
- How to use Context API to pass down a state while using a Router in React JS
- React - how to pass state to another component
- React router and this.props.children - how to pass state to this.props.children
- How to pass state values to initial values in formik in react js
- How to pass a state className variable to another component in react
- How to pass multiple states through react context api
- How to use React Context with useState hook to share state from different components?
- How to share React context state across separately mounted component trees
- How to keep React new Context API state when routing between Components?
- How do I pass all state variables inside react hooks to my child component
- How can ı pass function with state for react useContext
- pass a childs state through react context api to parent component
- How do I keep state persistant using local storage, react hooks, and Context Provider
- How to pass state in React from one class to another?
- How to use React Context API to have a state across multiple Routes?
- I can not get the state from react router Link component using useLocation. So how can I pass it?
- Gatsby: how to pass data to React Context at build time
- how to set react parent component state by a async function and then pass this state to child as props?
- How do I correctly add data from multiple endpoints called inside useEffect to the state object using React Hooks and Context API?
- how to pass outlet context to nested route in react router v6
- How to store react component in state and pass a callback function
- How to pass react hook state to another component for each click
- How to pass input values from a child Form component to the state of its parent component for submission with react hooks?
- React - How to call a function whenever a state in react context is updated?
- How to pass function from FUNCTIONAL to CLASS component and access it outside of render( without prop ), using context in react js?
- How to pass one state value to another state on initialization in react js
- How to pass a state to a Parent component if I have a button triggering the state in the 2nd Child in React
- How to pass state value to a callback function using React Hooks
More Query from same tag
- What is workflow of the React
- React material-table column resizable
- React Simple Unit Test for Reducer
- Javasript inside JSX of react js does not working
- Return value firestore onSnapshot in react
- Javascirpt Array Sorting Problem in reactJs
- Getting action is undefined whenever I start my React Application
- React Hooks: handle multiple inputs
- Something wrong with my way to fetch data?
- Passing data of a Child's form to Parent (App) in React
- How to update key value inside array when state changes?
- Formik setFieldError does not show message or prevent submit
- How to make useEffect rerun only on change of a single dependency?
- Jest testing React component using Electron-Remote in ElectronJS
- why rendering is delayed
- How can I nest an object in an object?
- Authenticate user in spring boot with react login form
- Why Firebase deploy's full react app instead of deploying build directory files?
- How to fix problem: TypeError: self.env.emit is not a function?
- Problem with ESLint, React/TS when trying to use export * syntax
- react is not recognized as an internal or external command or operable program or batch file
- React router + redux navigating back doesn't call componentWillMount
- React: Script tag not working when inserted using dangerouslySetInnerHTML
- jsx-a11y/no-static-element-interactions: how to make span clickable
- Decimal validation without any other character in JS
- Cannot read property 'type' of undefined create-react-app build
- Cannot assign new values to object in Javascript
- How to fix that eslint complain about typescript's path aliasing
- reactjs page reload on file upload
- how to get value onchange event when state data in object