Updating Objects in State with React JS 🚗

Posted by


In React, state is a crucial feature for managing data within a component. One common use case is updating objects within the state. In this tutorial, we will cover how to update objects in the state using React JS.

To get started, make sure you have a basic understanding of React components and state. If you’re new to React, I recommend checking out the official documentation for an overview of these concepts.

Let’s say we have a component that contains an object in its state like so:

import React, { Component } from 'react';

class MyComponent extends Component {
  state = {
    user: {
      name: 'John Doe',
      age: 30,
      email: 'johndoe@example.com'
    }
  }

  render() {
    const { user } = this.state;

    return (
      <div>
        <h1>{user.name}</h1>
        <p>{user.age} years old</p>
        <p>Email: {user.email}</p>
      </div>
    )
  }
}

export default MyComponent;

Now let’s say we want to update the email address of the user. We can achieve this by using the setState method and spreading the existing object in the state with the updated values.

Here’s how you can update the user’s email address:

class MyComponent extends Component {
  state = {
    user: {
      name: 'John Doe',
      age: 30,
      email: 'johndoe@example.com'
    }
  }

  updateUserEmail = (newEmail) => {
    this.setState({
      user: {
        ...this.state.user,
        email: newEmail
      }
    });
  }

  render() {
    const { user } = this.state;

    return (
      <div>
        <h1>{user.name}</h1>
        <p>{user.age} years old</p>
        <p>Email: {user.email}</p>
        <button onClick={() => this.updateUserEmail('newemail@example.com')}>
          Update Email
        </button>
      </div>
    )
  }
}

In the updateUserEmail method, we are using the setState method to update the email property of the user object in the state. We first spread the existing user object using the spread operator (...this.state.user) to maintain the other properties and then update the email property with the new value.

When the button is clicked, the updateUserEmail method is called with the new email address as an argument, which triggers a re-render of the component with the updated state.

This is how you can update objects in the state in React. Remember to use the setState method whenever you need to update the state to ensure that React properly re-renders the component with the updated data.

0 0 votes
Article Rating

Leave a Reply

19 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@BroCodez
5 hours ago

import React, { useState } from 'react';

function MyComponent(){

const [car, setCar] = useState({year: 2024,

make: "Ford",

model: "Mustang"});

function handleYearChange(event){

setCar(c => ({…c, year: event.target.value}));

}

function handleMakeChange(event){

setCar(c => ({…c, make: event.target.value}));

}

function handleModelChange(event){

setCar(c => ({…c, model: event.target.value}));

}

return (<div>

<p>Your favorite car is: {car.year} {car.make} {car.model}</p>

<input type="number" value={car.year} onChange={handleYearChange}/><br/>

<input type="text" value={car.make} onChange={handleMakeChange}/><br/>

<input type="text" value={car.model} onChange={handleModelChange}/><br/>

</div>);

}

export default MyComponent

@otabekmadaminov-z2i
5 hours ago

thank you bro

@justecho5760
5 hours ago

5:01 Bro explains the spread operator to the point even I can understand learning at 11:27 PM. That's some good teaching right there, bro 🙂

@YOLOcrazylife
5 hours ago

You can put this all into one function instead of having 3 separate functions by destructing the key on the object and by adding a name property that is the same name as the key on the object to each input tag. Ex. <input name=“year”/>

setCar((prev) => ({…prev, [e.target.name] : e.target.value
}))

@stefank5775
5 hours ago

Awesome video! Thanks for the detailed explanation, it was really helpful for me to understand working with object state.

@Haipster
5 hours ago

Wrote the same code as in the video, but the year, model and make are not changing in the browser.
Do we need to change / add something in server.js?

@nursultansagynbek4168
5 hours ago

Fantastic Bombastic

@ALMAMUN-mz7gy
5 hours ago

It's helpful and easy to learn. Enjoying Bro🥰🥰

@sayamajmal8094
5 hours ago

W in the chat

@crackrokmccaib
5 hours ago

Would something like this work to change the year, but keep everything else the same? setCar(c => c.year = event.target.value);

@wellyesorno
5 hours ago

i am sorry sir, can you make video of how to fetch data from JSON that is really complicated?

i have tables from flask that is about statistics data. I converted the data i have into table in pandas as df. And then when i make an API, the json is hard to be fetched and displayed into HTML.

i mean just imagine you have tables that have th, also nested th, and inside it you have data.

table
goofy quack baldur kramnik
g1 g2 g3 q1 q2 b1 b2 b3 b4 k1

its really hard, is there any alternative way to fetch it?

@hotwings9382
5 hours ago

Could've just used plain JavaScript for such a basic task.

@ofekcohen6559
5 hours ago

Bro you make node and express course?

@l213dhanesh3
5 hours ago

Code bro i love❤

@capslock3250
5 hours ago

Full course Kotlin please 🙏

@raitaskeen
5 hours ago

love from typescript lover…😁

@neerajtadhiyal3152
5 hours ago

thanks for the noice tutorial bro

@Dreamer2dev
5 hours ago

where is kotlin 💔💔

@vec_vance123
5 hours ago

love u brooo

19
0
Would love your thoughts, please comment.x
()
x