简体   繁体   中英

How to load another component inside a onChange function in ReactJS

I have this following code

var SelectOption = React.createClass({

  getInitialState: function() {
    return {
      data: []
    };
  },

  handleemployeeChange: function() {
        alert('sssss');

  },

  loadOptionfromServer: function() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function(data) {
        this.setState({
          data: data
        });
        console.log(data);
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },

  componentDidMount: function() {
    alert('sssss');
    this.loadOptionfromServer();
    //setInterval(this.loadCommentsFromServer, this.props.pollInterval);
  },


  render: function() {
    return ( < SelectOptionList data = {
        this.state.data
      }
      />
    );

  }
});

var SelectOptionList = React.createClass({

  render: function() {
    var commentNodes = this.props.data.map(function(list) {
      return ( < Addcontenttoselect id = {
          list.emp_ide_id
        }
        option = {
          list.emp_name
        } >
        < /Addcontenttoselect>
      );
    });
    return ( < select id = "select1"
      className = "form-control"
      data - placeholder = "Basic Select2 Box"
      onChange = {
        this.handleemployeeChange
      } > {
        commentNodes
      } < /select>
    );
  }
});

var Addcontenttoselect = React.createClass({
  render: function() {
    return ( < option value = "{this.props.id}" > {
      this.props.option
    } < /option>);
  }
});

ReactDOM.render( < div className = "col-md-3" > < h3 > Select Employee to Review < /h3><SelectOption  url="/appraisal / employeelist " pollInterval={70000}  /></div>, document.getElementById('select-box'));

So this component creates a Select Tag in the browser , I want to take the Value of the selected option and Call another component which will create a Table from a data got from API

Any leads please let me know

Thanks

With react you have multiple ways to pass around data to your components, it depends heavily on the use and the complexity of your application.

If you have a lot of components which need to know about the state/data of another component you should look at application architectures like flux or redux. Facebooks Flux

For some applications a full data flow architecture can be overkill so it depends on how you design your components. A common pattern is to have one component who handles the state/interactivity of your application. Your main component will hold all the business logic of your app and pass down functions to its child to eg change state. You can read more about this here Facebook thinking react

I did a little fiddle which adresses your challenge:

Fiddle

var Select = React.createClass({
render: function() {
var selectOptions = this.props.options.map(function(optionData) {
    return (
    <option key={optionData.id} value={optionData.id}>
        {optionData.name} 
    </option>
  );
});

return (
    <select 
    id="select1"
    className="form-control" 
    placeholder="Basic Select2 Box"
    onChange={this.props.onChange}
    > 
     { selectOptions } 
    </select>
   );
 }
});


  var SelectApp = React.createClass({
  // The main component holds the data
  getInitialState: function() {
  return {
    data: [],
    currentData: null
  }
},

componentDidMount: function () {
  this.loadOptions();
},

loadOptions: function () {
  var _this = this;
  return setTimeout(function() {
    _this.setState({data: [
    {
        id: 1,
      name: 'Foo Bar'
    },
    {
        id: 2,
      name: 'Bar Foo'
    }
  ]});
  }, 2000);
},

onChange: function (e) {
  var employeeId = e.target.value,
    _this = this,
    mockedData = [
    {
        id: 1,
      data: 'Good employee'
    },
    {
        id: 2,
      data: 'Not so good employee'
    }
  ];

// Mocking an additional data fetch
setTimeout(function () {
    var result = mockedData.find(function (employeeData) {
    return (employeeData.id == employeeId);
  });

  _this.setState({
    currentData: result
  });
}, 2000);

},

renderResult: function () {
if (this.state.currentData) {
    return (
    <div>
                <h4>Employee:</h4>
      <p>{this.state.currentData.data}</p>
    </div>
  );
}

return;
},

render: function() {
return (
  <div>
    <div>
      <h3> Select Employee to Review </h3>
      <Select url={this.props.url} options={this.state.data} onChange={this.onChange}/>
    </div>
            {this.renderResult()}
  </div>
 );
}
});

ReactDOM.render(<SelectApp url="/appraisal / employeelist " pollInterval={70000} />, document.getElementById('container'));

Edit:

renderResult: function () {
if (this.state.currentData) {
    return (
     <loadUserAppraisal url="something" empid={this.state.currentData.id} />
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM