Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update input value react

I have a list and edit button when user click edit button opening a new modal. I want to auto populate the selected username mail etc. Server side response is {this.test.name} i give him to input value to auto populate but when user click edit button ı can see the name but ı couldnt change the input how do ı do that ? Code :

<div className = "form__group field">
    <input type="input" className="form__field" placeholder="Name" name="name" id="name" value={this.test.name}  />
    <label htmlFor="name" className="form__label">Adı-Soyadı</label>
</div>
like image 391
Oğuzhan Avatar asked Oct 20 '25 13:10

Oğuzhan


2 Answers

If you are using hooks, you could do something like this:

import { useState } from "react"; // import useState

export default function App() {
  const [name, setName] = useState(""); // useState hook

  // handle change event
  const handleChange = (e) => {
    e.preventDefault(); // prevent the default action
    setName(e.target.value); // set name to e.target.value (event)
  };

  // render
  return (
    <div>
      <input value={name} type="text" onChange={handleChange}></input>
      <p>{name}</p>
    </div>
  );
}

First, we import the useState() hook to be able to use it, then we use it to store the state for the name value, you can give it an initial value of an empty string (""). In the handleChange() function, we prevent the default action and set the state to e.target.value, this is the input value passed by the event (as (e)). Every time the input changes, the state will update and the page will re-render.

You could check out my sandbox here

like image 60
axtck Avatar answered Oct 22 '25 03:10

axtck


  1. Keep the name in the state:
this.state = {
    name: '',
}

(setState when you have it, if you retrieve it only on mount)

  1. Pass value={this.state.name} to the input.
  2. Pass onChange={handleNameChange} to the input.
const handeNameChange = (e) => { 
    setState({ name: e.target.value });
}
like image 22
Paul Iovan Avatar answered Oct 22 '25 01:10

Paul Iovan