score:-13
@nowshad, are you trying to use with redux Then I suggest using the provider
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import todoApp from './reducers'
import App from './components/App'
const store = createStore(todoApp)
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
If you are using for just few components and you want to have values for all nested components as per your statement
For nested components can i have one provider and multiple consumers For an Example : 1 is an parent , 1.1 is a child to 1 and 1.1.1 is child to 1.1, Can i have provider to 1 and consumers to 1.1 and 1.1.1
then I suggest that you just pass a handler down as prop and once you want to change the state call the handler and it will change values throughout your components.(This should be done if you have just few child components, who all require the same values throughout)
***Using context, we can avoid passing props through intermediate elements***
As per React Docs
Don’t use context just to avoid passing props a few levels down. Stick to cases where the same data needs to be accessed in many components at multiple levels.
Check Official Docs as to why and why not use Context: https://reactjs.org/docs/context.html
Let me know if you still have issues or doubts as to why and how to use context
score:7
You need to write a function in the Provider component to update the State. To be exact Consumer can only use the values and the function(s) you wrote in the Provider component.
In Parent Component
updateReturnMessage = (ReturnMessage) => {
this.setState((prevState) => ({ ...prevState, ReturnMessage }))
}
<MyContext.Provider value={{ state: this.state, updateReturnMessage: this.updateReturnMessage }}>
// your code goes here
</MyContext.Provider>
In Child Component:
ClearData(e){
const val = e.target.value;
this.context.updateReturnMessage(val);
}
This function is similar to the action creators
available in Redux
and flux
score:33
Firstly, in order to update the context from the consumer, you need to access the context outside of the render function, For details on how to do this, check
Access React Context outside of render function
Secondly, you should provide a handler from Provider which updates the context value and not mutate it directly. Your code will look like
Parent.js
import MyContext from "./MyContext.js";
import Child from "./Child.js";
class Parent extends Component {
constructor(props) {
super(props);
this.state = {
Message: "Welcome React",
ReturnMessage:""
};
}
updateValue = (key, val) => {
this.setState({[key]: val});
}
render() {
return (
<MyContext.Provider value={{state: this.state, updateValue: this.updateValue}}>
<Child />
</MyContext.Provider>
)
}
}
Child
import MyContext from "./MyContext.js";
class Child extends Component {
constructor(props) {
super(props);
this.state = {
ReturnMessage:""
};
}
ClearData(e){
const val = e.target.value;
this.setState({
ReturnMessage:val
});
this.props.context.updateValue('ReturnMessage', val);
}
render() {
return (
<React.Fragment>
<p>{this.props.context.state.Message}</p>}
<input onChange={this.ClearData} />
</React.Fragment>
)
}
}
const withContext = (Component) => {
return (props) => {
<MyContext.Consumer>
{(context) => {
return <Component {...props} context={context} />
}}
</MyContext.Consumer>
}
}
export default withContext(Child);
score:37
Updating Context from a Nested Component
It is often necessary to update the context from a component that is nested somewhere deeply in the component tree. In this case you can pass a function down through the context to allow consumers to update the context:
theme-context.js
// Make sure the shape of the default value passed to
// createContext matches the shape that the consumers expect!
export const ThemeContext = React.createContext({
theme: themes.dark,
toggleTheme: () => {},
});
theme-toggler-button.js
import {ThemeContext} from './theme-context';
function ThemeTogglerButton() {
// The Theme Toggler Button receives not only the theme
// but also a toggleTheme function from the context
return (
<ThemeContext.Consumer>
{({theme, toggleTheme}) => (
<button
onClick={toggleTheme}
style={{backgroundColor: theme.background}}>
Toggle Theme
</button>
)}
</ThemeContext.Consumer>
);
}
export default ThemeTogglerButton;
app.js
import {ThemeContext, themes} from './theme-context';
import ThemeTogglerButton from './theme-toggler-button';
class App extends React.Component {
constructor(props) {
super(props);
this.toggleTheme = () => {
this.setState(state => ({
theme:
state.theme === themes.dark
? themes.light
: themes.dark,
}));
};
// State also contains the updater function so it will
// be passed down into the context provider
this.state = {
theme: themes.light,
toggleTheme: this.toggleTheme,
};
}
render() {
// The entire state is passed to the provider
return (
<ThemeContext.Provider value={this.state}>
<Content />
</ThemeContext.Provider>
);
}
}
function Content() {
return (
<div>
<ThemeTogglerButton />
</div>
);
}
ReactDOM.render(<App />, document.root);
The above example is straight from the React Context API docs v16.8.6, and is the recommended way to update a context value from a consumer. https://reactjs.org/docs/context.html#updating-context-from-a-nested-component
score:80
You could use the useContext hook to achieve this. It's quite easy to use it in the child elements of the Provider. As an example...
authContext.js
import { createContext } from "react";
const authContext = createContext({
authenticated: false,
setAuthenticated: (auth) => {}
});
export default authContext;
Login.js (component consuming the Context)
import React, { useContext } from "react";
import authContext from "./authContext";
export default () => {
const { setAuthenticated } = useContext(authContext);
const handleLogin = () => setAuthenticated(true);
const handleLogout = () => setAuthenticated(false);
return (
<React.Fragment>
<button onClick={handleLogin}>login</button>
<button onClick={handleLogout}>logout</button>
</React.Fragment>
);
};
Finally the index.js
import ReactDOM from "react-dom";
import React, { useState } from "react";
import authContext from "./authContext";
import Login from "./Login";
const App = () => {
const [authenticated, setAuthenticated] = useState(false);
return (
<authContext.Provider value={{ authenticated, setAuthenticated }}>
<div> user is {`${authenticated ? "" : "not"} authenticated`} </div>
<Login />
</authContext.Provider>
);
};
ReactDOM.render(<App />, document.getElementById("container"));
As you can see, it becomes quite easy to consume the data stored in the context using the useContext hook. Of course, as with every React hook, it only works with functional components.
If you want to see the code working. https://codesandbox.io/s/react-playground-forked-wbqsh?file=/index.js
Source: stackoverflow.com
Related Query
- How to update the Context value in a Provider from the Consumer?
- How to get the data from React Context Consumer outside the render
- How to set the default react context value as data from firestore?
- How to update the value coming from web socket server in React.js?
- How to update the correct state value in a parent component that gets its value from a child component using hooks in react?
- How to update the state of new context provider after ajax success
- How to mock a single value in a React Context provider while keeping the rest of values
- How can I update the value from the database in React
- How to use mapStateToProps to get a value from the state based on a context value?
- How can i update context value with the state value
- Updating State Context API, how to stop state from overwriting the current value in the reducer function?
- How to instantly update react state after replacing the value from array
- How do I update the default useSate value from a html input?
- How to "wait" for a React context provider that takes some time to build the value provided?
- React context API - can't update parent consumer from child provider
- ReactJS, how to edit a textarea and update the value when displaying the textareas from database?
- The array passed as the value prop to the Context provider (at line 8) changes every render. How i can fix this?
- React Context update value from provider wrapping child
- ReactJS: How To Get Input Value From The Prompt Box And Update It To Database
- How to update state in child component with context value from parent (class components)
- How to update state of component provider using the Context API
- How to update React Context from inside a child component?
- How to change the value of a Context with useContext?
- How to update the state of a sibling component from another sibling or imported component in REACT
- How do you update Formik initial values with the react context api values after an AJAX request?
- React Navigation: How to update navigation title for parent, when value comes from redux and gets updated in child?
- How to dynamically update the value for any input field with one event handler function, using hooks
- How to set defaultValue, value={this.props.value}, and update the value of a text input with React?
- How do I change a Formik TextField value from the outside of the From?
- Redux Toolkit w/ TypeScript: how can I properly type the return value from an async thunk
More Query from same tag
- Problem using map method with react (posts.map is not a function)
- can't do POST to api, error 400 using fetch
- How do you test object state in jest and enzyme?
- Redirect after completing an action with react-router-dom V5.+
- Elipses not getting added to the material UI tabs text
- Fluid images in .mdx file
- Redux saga: I need to pass argument to axios
- How can I make a (antd)Sub-Menu in a Horizontal Menu to align right while other menuItems are aligned left?
- Export 'Switch' was not found in react-router-dom
- React js not displaying '<a href...' as a link
- passport authentication works from postman but not with fetch()
- React/Redux Launch state change of another component
- How can i resize an image in a block display? (javascript or react)
- Having trouble calling function in parent from child in react
- Large numbers on calculator screen expanding past boundaries
- I need to set and send value of slider after onChange
- How does react batch works?
- How can I pass in the arguments to a function in react from within the html?
- Set width property array dynamically
- Not able to type in Input field in React.js. Why?
- How do you validate the PropTypes of a nested object in ReactJS?
- Is there a way to pass props by goBack() in React?
- How to make an array accessible under different functions in Javascript?
- Create Array List dynamically from Javascript Object
- Array gets undefined - React Redux
- How to get only the specific variation data to be display in react.js
- ReactJS dynamic pages from mongodb
- Switch Router with Navbar
- How to update one item without affecting other arguments?
- Websocket connection with apollo-server returns gibberish for connectionParams