gamda gamda - 4 months ago 26
React JSX Question

React instance before rendering

I am currently working on two

React
classes. One contains a map, and the other one contains buttons to turn layers on and off. I am integrating
propTypes
, one of them is the map so that the child can place markers on it.

componentDidMount() {
this.map = this.refs['map'].getMap()
// and other things
}


and in render() I pass the reference:

<LayerButtons map={this.map}></LayerButtons>


Here is the
ref
's map (below
LayerButtons
if it matters):

<Map height="480px" ref="map" zoom="13"/>


But this.props.map in
LayerButtons
is
undefined
. I added log statements to the class with the map. Right before the return statement in
render()
this.map is
undefined
as expected, and after assigning in
componentDidMount()
it is defined, also as expected. So I tried moving the assignment to
this.map
into the
render()
function, but before render, this.refs['map'] is undefined.

How can I initialize Map so it is defined when given to LayerButtons?

Answer

You should force component to rerender using this.forceUpdate(), after you assigned map in componentDidMount function:

componentDidMount() {
    this.map = this.refs['map'].getMap();
    this.forceUpdate();
    // and other things
}