a blog for those who code

Monday 14 January 2019

OnChange Event of DropDown on the Header in ReactJS

In this post we will be discussing about how OnChange Event of dropdown works in react.js on the header component and how it changes the contents of the child element. Let's say I have a ReactJS class which has a dropdown element displaying on the header and onchange of its values I want to update the contents of the body.

We have a DropDown Class (MySelectClass) in ReactJS, which returns a Select Tag with a number of options, in the Select Tag we have a value which shows the current selected value and we have an onchange event which will change the selected value and also call the props i.e. onChangeSelection as shown below.

class MySelectClass extends Component {
  constructor(props) {
    this.state = {
      selection: 'A'
  onChange(item) {
      selection: item
  render() {
      <Select value={this.state.selection}
        <Option value="A">A</Option>
        <Option value="B">B</Option>
        <Option value="C">C</Option>
        <Option value="D">D</Option>
        <Option value="E">E</Option>

MySelectClass.propTypes = {
  onChangeSelection: PropTypes.func

export default MySelectClass

Now the next is to call this component in my header class. Do note that we have to bind onChangeSelection (as this is the props of the child component) to call the appropriate function on teh parent component to do the changes based on the dropdown selection as shown below :

<MySelectClass onChangeSelection={this.loadData.bind(this)}/>

The function loadData is shown below which will be called on every change of the DropDown, here we are calling the getDataBySelection which will get the data based on the selected value of the dropdown.

loadData(selection) {
 const {dispatch} = this.props;

Thus we have learned how OnChange Event of dropdown works in react.js and how it changes the contents of the child element on changing the value of the dropdown.

No comments:

Post a Comment