0

I am new to React and using a simple table. I'm just testing to change an input text value when I select a button on the same row.

enter image description here

The code below is where I'm stuck. I'm trying to figure out how to change the state value "users" for this row when I click on the button. I'm trying to set the first_name to "Testing".

const [users, setUsers] = React.useState(null);

let usersList =
    businessUsersState.data.length > 0 &&
    businessUsersState.data.map((item: any, key: number) => {
                return (
        <tr key={key} data-account={item.account_id}>
            <td>
                <Form.Control name="first-name" type="input" placeholder="First Name" defaultValue={item.first_name} />
            </td>
            <td>
                <Button variant="primary" type="button" onClick={() => {
            debugger;
            const row = businessUsersState.data.map((item: any) => ({...item}));
            row[key].first_name = 'Testing';
            
            const row1 = usersList[key];

            
            //setUserRow(row);
            //setUsers(row);
        }}>
                </Button>
            </td>
        </tr>
    );
    });

setUsers(usersList);

I was reading the following link but I can't seem to get it to work. What can I try next?

5
  • What's the error you are getting? Commented Feb 25, 2022 at 1:05
  • Well, that's where I'm stuck. The value of users is the HTML data. When I set row[key].first_name = 'Testing'; I don't know how to change that rows state to update the data Commented Feb 25, 2022 at 1:13
  • I get the error: Cannot create property 'value' on a string 'John' so I tried row[key].first_name = 'Testing'; but it doesn't change the value Commented Feb 25, 2022 at 1:28
  • The problem is the state users aren't the simple array that businessUsersState.data contains. It's the whole table row elements. So what I'm trying to figure out is how to update that rows state data? Commented Feb 25, 2022 at 1:46
  • This is what the users state contains _owner:null _store:{validated: false} $$typeof:Symbol(react.element) key:'0' props:{data-account: '81ffdd69-fc50-49f0-8c84-b9ef64cfb046', children: Array(5), key: <accessor>} ref:null type:'tr' Commented Feb 25, 2022 at 1:51

1 Answer 1

1

Following React docs example of object and array in state

const uniqueId = () => {
  // always start with a letter (for DOM friendliness)
  let idstr = String.fromCharCode(Math.floor(Math.random() * 25 + 65));
  do {
    const ascicodeChar = Math.floor(Math.random() * 25 + 65);
    idstr += String.fromCharCode(ascicodeChar);
    idstr += Math.floor(Math.random() * 99);
  } while (idstr.length < 8);

  return idstr.toLowerCase();
};

const fakeData = [
  { id: uniqueId(), company: 'abc', contact: '[email protected]', country: 'China' },
  { id: uniqueId(), company: 'def', contact: '[email protected]', country: 'Japan' },
  {
    id: uniqueId(),
    company: 'ghj',
    contact: '[email protected]',
    country: 'Singapore',
  },
  {
    id: uniqueId(),
    company: 'ikl',
    contact: '[email protected]',
    country: 'Indonesia',
  },
  {
    id: uniqueId(),
    company: 'mno',
    contact: '[email protected]',
    country: 'Thailand',
  },
];

export default function App() {
  const [data, setData] = React.useState(fakeData);

  const handleEdit = (id) => {
    setData(
      data.map((t) => {
        // find item matched given id and mutate that item
        if (t.id === id) {
          return {
            id,
            company: `test${id}`,
            contact: `test${id}@gmail.com`,
            country: `test${id}`,
          };
        } else {
          return t;
        }
      })
    );
  };

  return (
    <div>
      <table>
        <tr>
          <th>Company</th>
          <th>Contact</th>
          <th>Country</th>
          <th>edit</th>
        </tr>
        {(() => {
          if (!data.length) {
            return <p>No data available</p>;
          }
          return data.map((i, index) => {
            return (
              <tr key={i.id}>
                <td>{i.company}</td>
                <td>{i.contact}</td>
                <td>{i.country}</td>
                <td>
                  {/* pass an id of row to edit fnc */}
                  <button onClick={() => handleEdit(i.id)}>edit</button>
                </td>
              </tr>
            );
          });
        })()}
      </table>
    </div>
  );
}

You could try to do the same above example.

Sign up to request clarification or add additional context in comments.

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.