0

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

2 Answers 2

1

Use placeholder instead of child text

<input type='text' name='fname' value={names.fname} onChange={UpdateData} placeholder='First Name' />
Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.