Set state in React Js

Viewed 448

I have an application with 3 inputs: name, percentage, and password. Also, I have a save button that should change the state, using the values from the inputs, in the parent component.

Using Ant Desing, I want to set the percentage, but I can't get the [e.target.name] from the Input Number from AntD.

How to solve this, and when I click the save button to update the state in parent component?.

code link: https://stackblitz.com/edit/react-ytowzg

3 Answers

Some notice points:

  • setState inside handler onInputNumber()
  • since the component is fully controlled, you don't need defaultValue
  • add value={state.percentage} props instead.
  • add percentage inside save()

Try it online: https://stackblitz.com/edit/react-5qrwcq

const Test = ({ user, setUser }) => {
  const [state, setState] = useState({ name: "", password: "", percentage: "1" });

  function onChange(e) {
    setState({
      ...state,
      [e.target.name]: e.target.value
    });
    console.log(state)

  }
  function onInputNumber(value) {
    setState({...state, percentage: value})
    console.log('changed', value);
  }

  function save() {
    setUser({ ...user, name: state.name, password: state.password, percentage: state.percentage });
  }

  return (
    <div>
      <input name='name' onChange={onChange} />
      <input name='password' onChange={onChange} />
      <InputNumber
      // defaultValue={100}
      min={0}
      max={100}
      value={state.percentage}
      formatter={value => `${value}%`}
      parser={value => value.replace('%', '')}
      onChange={onInputNumber}
    />
      <button onClick={save}>save</button>
    </div>
  );
};

You can pass the name from the onchange of the Antd input.

 <InputNumber
      defaultValue={100}
      min={0}
      max={100}
      formatter={value => `${value}%`}
      parser={value => value.replace('%', '')}
      onChange={(value) => onInputNumber('myinput', value)}
    />


function onInputNumber(name, value) {
    console.log('changed', value, name);
  }

In your save function, it appears that you haven't coded the update to percentage:

function save() {
    setUser({ ...user, name: state.name, password: state.password });
  }

Hope this helps.

Related