I'm trying to set a context in my React App, but somehow i can't acces context from childrens. This is the parent class:
import React from 'react'
import MenuBar from './MenuBar.js'
export default class App extends React.Component {
static childContextTypes = {
prop: React.PropTypes.bool
};
getChildContext(){
return {
prop: true
}
}
render() {
return (
<div>
<MenuBar />
</div>
)
}
}
And here is my children class:
import React, { Component } from 'react';
export default class MenuBar extends Component {
constructor(props, context){
super(props,context)
console.log(this.context)
console.log(context)
}
render() {
console.log(this.context)
return (
<div>MenuBar</div>
);
}
}
All the console.log's return an empty object, am i doing something wrong?
You have to specify contextTypes on MenuBar for any context properties to be passed to it.
class MenuBar extends React.Component {
// you're missing this
static contextTypes = {
foo: React.PropTypes.bool,
};
constructor(props, context){
super(props,context)
console.log(this.context)
console.log(context)
}
render() {
console.log(this.context)
return (
<div>MenuBar</div>
);
}
}
See this working example.
omg... thank you!!
Most helpful comment
You have to specify
contextTypesonMenuBarfor any context properties to be passed to it.See this working example.