ThomasReggi
ThomasReggi

Reputation: 59345

Access other component refs from within component

I'm looking for a way for two components to talk to each other. I simply want it so that when <InputCheckboxAll/> is checked or unchecked it will checked or unchecked all <InputCheckbox/> components.

var InputCheckboxAll = React.createClass({
  render: function () {
    return (
      <input type='checkbox' {...this.props}/>
    )
  }
})

var InputCheckbox = React.createClass({
  render: function () {
    return (
      <input type='checkbox' {...this.props}/>
    )
  }
})

<InputCheckboxAll ref='masterCheckbox'/>
<InputCheckbox masterRef='masterCheckbox'/>
<InputCheckbox masterRef='masterCheckbox'/>
<InputCheckbox masterRef='masterCheckbox'/>

How from within the <InputCheckboxAll> component can I select all refs with masterCheckbox on the dom?

Upvotes: 0

Views: 86

Answers (1)

J. Mark Stevens
J. Mark Stevens

Reputation: 4945

Pass handler to InputCheckboxAll and state to InputCheckbox.

    var InputCheckboxAll = React.createClass({
        handleChange: function(event) {
            this.props.handleChange(event);
        },
      render: function () {
        return (
          <input type='checkbox' {...this.props} onChange={this.handleChange} />
        )
      }
    })

    var InputCheckbox = React.createClass({
      render: function () {
            var checkedValue = this.props.allChecked ? true : this.state.checked;
        return (
          <input checked={checkedValue} type='checkbox' {...this.props}/>
        )
      }
    })

    var CheckMaster = React.createClass({
        getInitialState: function() { return {allChecked: false}; },
        handleChange: function(event) {
            this.setState({allChecked: event.target.value});
        },
        render: function () {
            return (
                <div>
                    <InputCheckboxAll handleChange={this.handleChange}/>
                    <InputCheckbox allChecked={this.state.allChecked}/>
                    <InputCheckbox allChecked={this.state.allChecked}/>
                    <InputCheckbox allChecked={this.state.allChecked}/>
                </div>
            )
        }
    })

Upvotes: 1

Related Questions