Ali
Ali

Reputation: 1217

react-native: How can I change parameters from a child component in react context?

My root react-native is something like this: I try to work with CONTEXT API.

import { ContextProvider} from './ContextProvider';
export default class App extends React.PureComponent {
  render() {
    return (
      <ContextProvider>
        <Navigator />
      <ContextProvider>
    );
  }
}

I create a simple context component like this:

ContextProvider:

export const ParamContext = React.createContext({ param:0 });

export class ContextProvider extends React.PureComponent {
  state = {
    param: 0,
  };

  render() {
    return (
      <ContextProvider.Provider value={this.state}>
        {this.props.children}
      </ContextProvider.Provider>
    );
  }
}

I can print the value of param in a children component with this code:

import { ParamContext } from './ContextProvider';
export default class child1 extends React.PureComponent  {
   static contextType = ParamContext;
   render(){
       console.log(this.context.param)
   }
}

it works.

Now this is my question.

How can I change param with a child component in my code?

Upvotes: 1

Views: 1280

Answers (1)

user6612182
user6612182

Reputation:

The offical React documentation for Context suggests passing a function in addition to your value with which you can change the value:

// ContextProvider

export const ParamContext = React.createContext({ param:0, setParam: () => {} });

export class ContextProvider extends React.PureComponent {
    state = {
        param: 0
    }

    setParam = (param) => this.setState({ param });

    render() {
        const { setParam } = this;
        return (
            <ParamContext.Provider value={{...this.state, setParam }} >
                {this.props.children}
            </ParamContext.Provider>
        );
    }
}


// ContextConsumer
const ContextConsumer = (props) => {
    return (
        <ParamContext.Consumer>
            {({param, setParam}) => <Button onPress={() => setParam(param + 1)} title={`Current value: ${param}`} />}
        </ParamContext.Consumer>
    );
}

This example will increase the param by the value 1 on each click of the button.

Upvotes: 1

Related Questions