0

I need some help. I am new to Reactjs and I am trying to map nested object to an input filed so when the user type something it will be map to the nested object field name.

This is the data I am trying to access.

const [details, setDetails] = useState(
    {
        firstName: '',
        lastName: "", 
        email: '', 
        dataOfBirth: '', 
        phoneNum: '',
        employeeAddress:
            {
                street: '',
                city: '',
                state: '',
                zipcode: 0
            }
    })

input field form I have try the below code and I it's not working

<div className="form-group">
     <label htmlFor="" className="street">Street</label>
     <input type="text" name="street" id="street"
            onChange={e => setDetails({...details.employeeAddress, street: e.target.value})}
            value={details.employeeAddress.state}
      />
</div>

Example the below code work because it not nested inside an object.

<div className="form-group">
     <label htmlFor="" className="firstName">First Name</label>
     <input type="text" name="firstName" id="firstName"
            onChange={e => setDetails({...details, firstName: e.target.value})}
            value={details.firstName}
     />
</div>
1
  • You are setting street but assigning state as the value? Commented Apr 22, 2021 at 14:52

2 Answers 2

1

you need to also spread the employeeAddress object like so

onChange={e => setDetails({ ...details, employeeAddress: { ...details.employeeAddress, firstName: e.target.value } })}
Sign up to request clarification or add additional context in comments.

Comments

1
const updateEmployeeAddress = e => {
    setDetails({
        ...details, 
        employeeAddress: { 
            ...details.employeeAddress, 
            [e.target.name]: e.target.value
        }
    })         
}

<div className="form-group">
     <label htmlFor="" className="street">Street</label>
     <input 
         type="text" 
         name="street" 
         id="street"
         onChange={updateEmployeeAddress}
         value={details.employeeAddress.street}
      />
</div>

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.