Home > Enterprise >  How to create dynamic states and update it in react?
How to create dynamic states and update it in react?

Time:08-31

I have list of data getting fetched from the API and each index in data is creating a <div> which consist of some information and button along with it.

Now when I click on button, a textarea and submit button should open for that <div> and closes when clicked again.

I tried to create this here.

To achieve this, I am creating n number of states and update the state when user click the button.

How can I achieve this and where am I going wrong ?

CodePudding user response:

This is a working example of what you're looking for:

const { useState } = React;

const Counter = () => {
  const [count, setCount] = useState(0);
  
  const data = [
    {"id":100},
    {"id":200},
    {"id":300},
    {"id":400},
  ];
  
  const [show,setShow] = useState([]);
  
  const handleClick = id => e => {
    const showCopy = show;
    
    if(show[id]){
      showCopy[id] = false;
    } else {
      showCopy[id] = true;
    }
    
    setShow(showCopy);
  }

  return (
    <div>
      {
        data.map((k,v) => (
          <div key={v}>
            <div>
              <p>Data{v 1}</p>
              <p>Some More Information</p>
            </div>
            <button onClick={handleClick(v)}>Update</button>
            <br/>
            {
              show[v] ? <div>
                  <textarea></textarea>
                  <button id={v}>Delete</button>
              </div> : <></>
            }
            <hr/>
            
          </div>
        ))
      }
    </div>
  )
}

ReactDOM.render(<Counter />, document.getElementById('app'))

A couple things were wrong in your sample code:

  1. Improper use of dot operators instead of brace operators

The JS dot (.) operator is used to access named attributes associated with the given JS object. In these particular cases, the values v and id are dynamic, and not the true names of the attributes desired. Using the brace [] operators allows you to access the dynamic value stored in the variable.

  1. Improper array state update

In your example, the code you had written was creating a new array based on the contents of the previous array and adding a new object every time with a literal attribute named id. In the updated code, a copy of the original state array is created and the desired boolean value with index id is modified.

  • Related