MAYANK KUMAR
MAYANK KUMAR

Reputation: 408

Error in dynamically setting state in React Hooks

Hi I am dynamically trying to set input values in react-hooks concept, but I am encountering an error. Could someone help me with this:

Code:

import React,{useState} from 'react';

function ObjectHook() {
    var [names,setName]=useState({fname:'',lname:''});
    let UpdateData = (event) =>{
        setName({...names,[event.target.name]:event.target.value})
    }
    return(
        <div>
            <input type='text' name='fname' value={names.fname} onChange={UpdateData}>First Name</input>
            <input type='text' name='lname' value={names.lname} onChange={UpdateData}>Last Name</input>
            <h1>{names.fname}</h1>
            <h1>{names.lname}</h1>
        </div>
    )
}

export default ObjectHook;

here is the error: enter image description here

Upvotes: 0

Views: 69

Answers (2)

Ari
Ari

Reputation: 1703

inputs don't accept children. Meaning you can't do this ...

<input>text</input>

You can use the input placeholder attribute, but placeholders are not accessible.

The best thing to do is use a label.

<label>
  First Name<
  <input />
</label>
<label>
  Last Name<
  <input />
</label>

Upvotes: 1

Use placeholder instead of child text

<input type='text' name='fname' value={names.fname} onChange={UpdateData} placeholder='First Name' />

Upvotes: 1

Related Questions