Unable to change the value in the object

Viewed 58

My objective is to change the value of the object to true or false while onchanging the checkbox.

Object contains:

{
  id: '12497wewrf5144',
  name: 'ABC',
  isVisible: 'false'
}

Here is the code:

import React, { Component } from 'react'

class Demo extends Component {
  constructor(props) {
    super(props)
    this.state = {
      demo: {}
    }
  }

  componentDidMount() {
    axios
      .get('/api/random')
      .then(res => {
        this.setState({ demo: res.data?.[0] })
      })
      .catch(error => {
        console.log(error)
      })
  }
  render() {
    return (
      <div>
        <h1>{this.state.demo.name}</h1>
        <input type="checkbox" value={this.state.demo.value} />
      </div>
    )
  }
}

export default Demo

I don't know what to write in onchange method for checkbox to only change the value within the object.

Can anyone help me in this query?

3 Answers
       <input
          type="checkbox"
          value={this.state.demo.value}
          onChange={(event) => {
            this.setState((prevState) => ({
              ...prevState,
              demo: { ...prevState.demo, isVisible: event.target.checked }
            }));
          }}
        />

Given your state ends up looking like

this.state = {
  demo: {
    id: "12497wewrf5144",
    name: "ABC",
    isVisible: "false",
    value: false
  }
};

You can create a change handler as such

changeHandler = e => {
  e.preventDefault();
  const { checked } = e.target;
  this.setState(prevState => ({
    ...prevState, // <-- spread existing state
    demo: {
      ...prevState.demo, // <-- spread existing demo
      value: checked, // <-- save the input's checked value
    }
  }))
}

Attach the changeHandler to the onChange event callback

<input
  type="checkbox"
  onChange={this.changeHandler}
  value={this.state.demo.value}
/>

Ciao, you could use onClick event like this:

...
handleClick = (e, data) => {
    const demo = { ...this.state.demo };
    demo.isVisible = !demo.isVisible;
    this.setState({ demo });
}

...
<input type="checkbox" value={this.state.demo.value} onClick={((e) => this.handleClick(e, data))}/>
...
Related