context Api shows no value in the Consumer

Asked

Viewed 79 times

1

I started to study context api now, I believe I am making my code with the same structure as the tutorials, but the value target Component receives nothing, there is only a blank where it should have it.

import React, { Component } from 'react';

const CarContext = React.createContext();

function context(){
  return(
    <CarContext.Provider value='car'>
    </CarContext.Provider>
  );
}

function App(){
  return(
    <CarContext.Consumer>
      {value => (
        <p>a{value}</p>
      )}
    </CarContext.Consumer>
  )
}

export default App;

What is missing for the code to work?

  • CarContext.Provider and CarContext.Consumer what these two components would be?

  • are the context Provider and Consumer, which are the components of sending and receiving global data

  • Are you seeing these components as? because the Consumer really doesn’t do anything!

  • Consumer shows what’s inside it, I tidied up, actually had forgotten to call the context function before it, calling it worked

1 answer

1


I’m not sure I understood what you wanted to do, but how you must have studied, the Context.Provider passes the data to the child components through the Context.Consumer. In my vision, the Providershould be at the highest node of the component tree, which in case would be the App, and your code is changed. I made an example of code to help you.

const CarContext = React.createContext();

class CarComponent extends React.Component {
	render() {
	  return (
		<CarContext.Consumer>
		  {value => <p>My Car: {value}</p>}
		</CarContext.Consumer>
	  );
	}
}

class App extends React.Component {
	render() {
	  const value = "BMW";
	  return (
		<CarContext.Provider value={value}>
		  <CarComponent />
		</CarContext.Provider>
	  );
	}
}

ReactDOM.render(<App />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>

I hope I’ve helped! '-'

  • In fact I left as the highest layer the same context what I had done wrong was not to have called the context before calling the Sumer, but thanks for the help, your version would also work, but is that I want to leave the context in the highest layer even :D

  • Nice example Julia, our site has a way to put the code running as demonstrated in my edition to contribute your response.

  • 1

    Thank you, @Virgilionovic.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.