@
@
@Richswitch2018-06-22 08:55:23
JavaScript
@Richswitch, 2018-06-22 08:55:23

How to pass data from bottom to top using React's Context API?

Hey!
I'm trying to implement Context Api in my project. And now I'm trying to understand: is it possible to pass data from bottom to top , i.e. from child components to parent or from Consumers to Provider ?
Example:
React.createContext

export const eventData = {
  topic: "defaultTopic",
};

export const CreateEventFormContext = React.createContext(eventData);

There is a typical input for entering text. has not yet been used valueFromProviderin any way. ConsumerBut I want to pass an attribute value valuethat changes dynamically using handleChangein Provider. Well, then from ProviderI plan to transfer data to ControlForm.jsx and from there I will send an array of data to the database.
CreateEventFormConsumer
...
  handleChange(event) {
    this.setState({ value: event.target.value });
  }
...
  <CreateEventFormContext.Consumer>
     {valueFromProvider => (
         <input type="text" value={this.state.value} onChange={this.handleChange} />
     )}
  </CreateEventFormContext.Consumer>

CreateEventFormProvider
<CreateEventFormContext.Provider value="HELLO WORLD">
            <Topic />
      </CreateEventFormContext.Provider>

So I passed the string HELLO WORLDto valueFromProviderin my Consumer. But how can I do the same in reverse? When I started to delve into it, Context ApiI thought that this would save me from callbacks, but so far, apart from the callback, I don’t see any other option to transfer data up.
How to pass data from bottom to top using React Context API?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Spirin, 2018-06-22
_

The Context API is used to pass context, not to manage state. Read about Redux .

D
DarthJS, 2018-06-22
@DarthJS

Centext Api is a little bit different. Just throw the method inside:
and already in the parent component, where you declared it, catch value:
handleChange = (e) => e.target.value;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question