I’m trying to make my context work properly.
I’ve added it and it works as it should if I pass a string as a property to the state. However, I want to pass a prop as the state.
So this works:
export class DataProvider extends Component {
constructor(props) {
super(props);
this.state = {
continent: props.continent,
};
this.updateState = this.updateState.bind(this);
}
updateState() {
this.setState({ continent: this.props.continent});
}
componentDidMount() {
console.log(this.props.continent);
this.updateState();
}
render() {
return (
<DataContext.Provider value={{ state: this.state }}>
{this.props.children}
</DataContext.Provider>
);
}
}
But this does not work (results in undefined)
this.state = {
continent: props.continent,
};
Results in “undefined” when I try to access it.
I get the prop from a component named “Africa”, which does this:
const Africa = ({}) => {
return (
<div>
<DataProvider continent={["Africa"]} />
........irrelevant code
It successfully passes to my DataProvider component.
But, as I stated, when I try to pass that as a property for my state, it results in “undefined”.
class JumbotronPage extends Component {
static contextType = DataContext;
render() {
console.log(this.context)
A(DataProvider), B(Africa), C(JumbotronPage)
I’m not sure if it’s because A and B recognizes each other.
B and C does not.
So whenever I access C from A, B gets re-rendered, resulting in giving C nothing as state. Does that make sense?
Please, forgive me for being very green and new to React. I hope I make some sense.
This is part of my App.js:
<Route exact path="/Login" component={Login} />
<Route exact path="/Jumbotron">
<DataProvider>
<JumbotronPage />
</DataProvider>
</Route>
<Route exact path="/CreateNewMemories" component={renderForm} />
I created a gist, if someone has the time an patience to have a look at my abomination.
https://gist.github.com/kalleftw/e79412034eafd29a2e26b1af24149e67
I understand that using this technique for passing contexts is quite outdated, however, I am very new to React and this was the way that I understood (best).