Home > Net >  Replacing value input by user with value assigned with state in React
Replacing value input by user with value assigned with state in React

Time:10-29

I have a reactstrap Input field

        <Input
          onChange={handlePriceInputChange}
          type="number"
          defaultValue={price}
          innerRef={register("price", { required: true })}
        ></Input>

which I am filling with a default "" state called price in defaultValue.

  const [price, setPrice] = useState("");

I set this value with a function in onChange


  const handlePriceInputChange = (ev) => {
    setPrice(parseInt(ev.target.value));
  };

and also clicking some div containers trigger a function handleSelectedBox

  const handleSelectedBox = (ev) => {
    setSelected(ev.target.getAttribute("data-boxprice"));
    setPrice(parseInt(ev.target.getAttribute("data-price")));
  };

When I fill the input field manually and then trigger the buttons that should trigger handleSelectedBox, the state price changes, but the value stays the same on the client-side.

How could I force handleSelectedBox to change the value within input even if such value was set manually?

CodePudding user response:

So the answer is to use value instead of defaultValue :

        <Input
          onChange={handlePriceInputChange}
          type="number"
          value={price}
          innerRef={register("price", { required: true })}
        ></Input>
  • Related