Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to re-render in a React Functional Component According to a onChange?

I would like to reflect a value inside the div tag that you choose from the following select tag right after the value changes by onChange when you use a React Functional Component, so you can't use setState function. Under the prerequisite, how do you call render method (or, re-render the value inside the div) according to the value change? Any idea?

<select onChange={foo}>
  <option value="1">1</option>
  <option value="2">2</option>
</select>

<div>{value}</div>
like image 397
diveintohacking Avatar asked Nov 22 '25 21:11

diveintohacking


1 Answers

  1. Maintain the state in the parent component, pass it as props to the functional component to show the value
  2. Pass the onChange from parent to functional child component as well.

Like this,

function Child({ value, onChange }) {
  return (
    <div>
      <select onChange={onChange}>
        <option value="1">1</option>
        <option value="2">2</option>
      </select>
      <div>{value}</div>
    </div>
  );
}

class Parent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: ''
    };

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    this.setState({
      value: e.target.value
    });
  }

  render() {
    return <Child value={this.state.value} onChange={this.handleChange} />;
  }
}
like image 183
Anthony Liu Avatar answered Nov 25 '25 11:11

Anthony Liu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!