Home > Net >  React saving inputs to state
React saving inputs to state

Time:01-28

i am new to react and am trying to figure out something for my classes. I have a form that i need to get the information from all the inputs and save it in a state. I have tried reading the react docs, different answers from here and a few youtube tutorials but cant seem to figure it out. Am looking for some help to atleast tell me what im doing wrong. Thanks in advance and sorry if this question seems stupid

const [name,setName] = useState("");

return (
    <div className="App">
       <div >
          <label>Campaign Name</label>
          <input type='text'  required maxLength='20' onChange={setName()} className="input"/>
       </div>  

CodePudding user response:

Here is an example of how I set state for input values.

Make sure to set this outside the component (before defining the component).

let initialValues = {
  city: ''
}
const [quote, setQuote] = useState(initialValues)
<input type="text"
  value={ quote.city || "" }
  name="city"
  onChange={ onChange } />
const onChange = (e) => {
  setQuote({...quote, [e.target.name]: e.target.value});
};

you can have as many key values inside the initialValues const. Make sure you define the name of the input along with the value pointing to the state object and an onChange event that handles the setting. Happy Coding!

CodePudding user response:

To make a simple change with the code that you have, you can simply rewrite the onChange method for the input element.

onChange={(e) => setName(e.target.value)}

CodePudding user response:

Short explain:

What you are doing wrong is onChange={setName()}. It must be onChange={(...) => setName(...)} or onChange={setName}.

Long explain:

When you write code as onChange={setName()}, the code will running like 2 below lines of code:

const tempValue = setName() // this will run setName with no parameter and then set tempValue = undefined
...onChange={tempValue}...  // or equal onChange={undefined}, which make no sense

The onChange here accept a function which accept event param, so you must write it like this:

function eventHandler(event) {...}
or
const eventHandler = event => ...
...onChange={eventHandler}...

More specific, in your case, it needs to be like this:

const eventHandler = event => setName(event.target.value)
...onChange={eventHandler}...
or
...onChange={event => setName(event.target.value)}...

CodePudding user response:

Based on the code that you have provided, it seems that you are not setting your state to anything on change. A good practice would be to establish a handler, that will be triggered and set the respective value.

const [name,setName] = useState("");
    
const nameChangeHandler = (e) => {
    setName(e.target.value)
};

 return (
  <div className="App">
    <div >
      <label>Campaign Name</label>
      <input type='text'  required maxLength='20' onChange={nameChangeHandler} className="input"/>
</div>  

  •  Tags:  
  • Related