Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React change state based on select option

I need to store the distance value in state. It should equal the distance passed as props + the distance selected by user. How to do this?

class Distance extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      distance: 0
    };
  }

  onChange = e => {
  }

  render() {
    return (
      <div>
        <p>{this.props.distance}</p>
        <select onChange={this.onChange}>
          <option>30km</option>
          <option>50km</option>
          <option>70km</option>
        </select>
      </div>
    );
  }
}
like image 275
Andrew Avatar asked Apr 09 '26 21:04

Andrew


1 Answers

Using functional components, you can do this:

  const Distance = () => {
  const [distance, setDistance] = useState("");

  return (
    <div>
      <p>{distance}</p>
      <select onChange={(e) => setDistance({distance: e.target.value})}>
        <option value="30">30km</option>
        <option value="50">50km</option>
        <option value="70">70km</option>
      </select>
    </div>
  );
};

export default Distance;

In a case where you have multiple inputs, and only distance is a select input, you can do this to update distance while maintaining the values of other inputs:

  const Distance = () => {
  const [input, setInput] = useState({
     distance: "",
     time: "",
     place: "",
  });

  return (
    <div>
      <p>{distance}</p>
      <select onChange={(e) => 
           setInput({ ...input, distance: e.target.value }}
       >
        <option value="30">30km</option>
        <option value="50">50km</option>
        <option value="70">70km</option>
      </select>
    </div>
  );
};

export default Distance;
like image 93
DhanteyUD Avatar answered Apr 12 '26 10:04

DhanteyUD