React: Why is `this.props.children` undefined?

I am creating an electronic resistance calculator with ReactJS. I have a composite component declared like this:

var ResistanceCalculator = React.createClass({ getInitialState: function() { return {bands: [0,0,0,0,0]} }, componentDidMount: function() { console.log(this.props.children); // => undefined }, render: function() { return ( <div> <OhmageIndicator bands={this.state.bands} /> <SVGResistor bands={this.state.bands} /> <BandSelector band={1} /> <BandSelector band={2} /> <BandSelector band={3} /> <BandSelector band={4} /> <BandSelector band={5} /> </div> ); } }); 

BandSelector displays the <select> elements, and when one changes, I want to update the state of the ResistanceCalculator . So I thought I needed to bind an event listener to the ResistanceCalculator children. However, this.props.children seems empty. Why is this?

+7
javascript reactjs
source share
1 answer

Rule of thumb: everything in this.props is passed to you from the parent. So you are using this.props.children wrong way. If I had something like this:

 <Todos><div /><div /></Todos> 

then for the Todos component this.props.children will be an array of divs .

Here you can specify simple callbacks ( working example ):

 /** @jsx React.DOM */ var ResistanceCalculator = React.createClass({ getInitialState: function() { return {bands: [0,0,0,0,0]}; }, handleBandSelectionChange: function(bandIndex, newValue) { // for the sake of immutability, clone the array here var bands = this.state.bands.slice(0); bands[bandIndex] = newValue; console.log(bandIndex, newValue); // yep, seems to work this.setState({bands: bands}); }, render: function() { return ( <div> <OhmageIndicator bands={this.state.bands} /> { this.state.bands.map(function(value, i) { return ( <BandSelector band={i} onChange={this.handleBandSelectionChange}/> ); }, this) } </div> ); } }); var BandSelector = React.createClass({ handleChange: function(e) { if (this.props.onChange) this.props.onChange(this.props.band, e.target.value); }, render: function() { return ( <select onChange={this.handleChange}> <option value="1">1</option> <option value="2">2</option> </select> ); } }); 

I listen to the usual onChange event from select, then in the handler I call my parent handler ( handleBandSelectionChange ). Note that for the parent ( ResistanceCalculator ) the event should not be onChange ; it can be any name if the child calls him. Better call it onChange .

As a side note, this.props.children used for shell components that want to transparently display their content while doing some work on their own.

+12
source share

All Articles