Groovietunes Groovietunes - 3 months ago 19
React JSX Question

React parent function calls child's nested componentDidMount function?

I'm using D3 with react and I need to run the resize function whenever handleClick() is run by the parent or perhaps simply if the toggle state is changed. What is the best way to approach this?
Parent Component

class Wrapper extends Component {
constructor(props) {
super(props);
this.state = {
toggle: true
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
if (!this.state.toggle) {
this.setState({toggle: true})
} else {
this.setState({toggle: false})
}
}
render() {
const toggled = this.state.toggle ? 'toggled' : '';
return (
<div id="wrapper" className={toggled}>
<UnitedStatesMap />
</div>
);
}
}


Child Component

class UnitedStatesMap extends Component {
constructor() {
super();

this.state = {
activeState: d3.select(null)
};
}

shouldComponentUpdate() {
return false;
}

componentDidMount() {
function resize() {
if(activeState[0][0]) { reset() };
width = document.getElementById('page-content-wrapper').offsetWidth;
height = width * mapRatio;

projection
.translate([width / 2, height / 2])
.scale(width);

svg
.style('width', `${width}px`)
.style('height', `${height}px`)

svg.select('rect')
.attr('width', width)
.attr('height', height)

g.selectAll('.state').attr('d', path);
}
render() {
return (
<div id="map" ref="map"></div>
)
}
}

Answer

In Wrapper pass toggle to UnitedStatesMap

<UnitedStatesMap toggle={this.state.toggle} />

In UnitedStatesMap add

componentWillReceiveProps(nextProps) {
  if (this.props.toggle !== nextProps.toggle) {
    // call resize
  }
}

Obviously, you'll have to move your resize function into its own instance method and then just call it in componentDidMount and componentWillReceiveProps.

Comments