How to edit the TextField value, with the value is already pre defined

Viewed 630

I have a form that comes with some data from a country. By default, the data is read-only, if the user wants to change the value, click on the edit button.

The problem is that I am not able to edit the value in TextInput, by default, the value value is already pre defined. I try to edit the value through onChange(), but it doesn't work.

Everything I type does not appear in the Input field.

Here's my code, I put in CodeSandBox: https://codesandbox.io/s/polished-water-muq69?file=/src/App.js

I'm using TextField from react-material.

form

Can someone help me to update that´s values? Thank you in advance.

4 Answers

As others stated, the problem is that you need onChange and value to point at same value/variable in state.

As a step further, I would clean all these variables in state and use only one method to change the properties (if for example you have many fields and the code gets long enough)

  const changeField = (name, value) => {
    let newCountryInfo = [...countryInfo];
    newCountryInfo[0].data.Country[0][name] = value;
    setCountry(newCountryInfo);
  };

and in each TextField you add sth like the following depending on the field

  onChange={event => {
    changeField("name", event.target.value);
  }}

Check this codesandbox link

I'm not a React expert but it seems that the react component is overriding all the changes that are being typed. you can see it on the dev console, just delete the value="brazil" and try to type something, the value="brazil" will pop up back to the input tag. I can suggest to replace the value by placeholder. In that way the user sill still see the old value, and will be able to type new one.

Use State property as a value

const [countryName, setCountryName] = useState("");

<TextField
className={classes.field}
disabled={disabledField}
label="Name"

value={countryName}

onChange={event => {
  setCountryName(event.target.value);
}}
variant="outlined"
InputLabelProps={{
  shrink: true
}}
/>

and inside useState("") , define initial value or predefined value.

The issue is here:

value={item.data.Country[0].name}

whatever you have set in value attribute will remain in that. So instead of passing your API response here pass a state value in it and update that state on the change of input value ( 2 way data binding ). It will solve the issue.

Changes you have to made:

const [countryName, setCountryName] = useState("");

onChange={event => {
  setCountryName(event.target.value);  // This will update the state
}}
value={countryName}  // updated state value is used here
Related