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.
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 cant seem to get it to work. Any help is appreciated.
CodePudding user response:
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.