Reputation: 110
I'm not sure if this is the right way to push table element in React, but I've been doing this all the time. So this for loop below will get executed everytime re-render occurs or in this case when I change my input. what if I have like 100 Input?
Questions:
function App() {
const [inputs,setInputs] = useState({input1:'',input2:'',input3:''})
function handleOnChange(e){
const {name,value} = e.target
setInputs(prev => ({...prev, [name]:value}))
}
let tableElement = []
for(let i = 1; i <= 3; i++){
tableElement.push(<tr key={i}>
<td><Input value={inputs[`${i}`]} name={`input${i}`} onChange={handleOnChange} /></td>
</tr>)
}
return (
<div>
<Table>
<tbody>
{tableElement}
</tbody>
</Table>
</div>
);
}
export default App;
Upvotes: 0
Views: 339
Reputation: 202686
Given code:
let tableElement = []
for (let i = 1; i <= 3; i++){
tableElement.push((
<tr key={i}>
<td>
<Input value={inputs[`${i}`]} name={`input${i}`} onChange={handleOnChange} />
</td>
</tr>
))
}
return (
<div>
<Table>
<tbody>
{tableElement}
</tbody>
</Table>
</div>
);
Questions:
- Is this the right way to draw table element?
It isn't wrong, though it may not be the most common way to render out an array to JSX. Typically you may opt to map an array to JSX
const tableElement = [...Array(3).keys()].map((i) => (
<tr key={i}>
<td>
<Input value={inputs[`${i}`]} name={`input${i}`} onChange={handleOnChange} />
</td>
</tr>
));
return (
<div>
<Table>
<tbody>
{tableElement}
</tbody>
</Table>
</div>
);
Or directly in the JSX
return (
<div>
<Table>
<tbody>
{[...Array(3).keys()].map((i) => (
<tr key={i}>
<td>
<Input
value={inputs[`${i}`]}
name={`input${i}`}
onChange={handleOnChange}
/>
</td>
</tr>
))}
</tbody>
</Table>
</div>
);
- wouldn't re-render cause bad performance especially if you have some kind of loop before return?
I suppose there is a potential for poor performance, but due to the nature of the UI needing to map out a bunch of array elements when the component renders this is work that would be necessary anyway.
React is already pretty optimized out-of-the-box. It uses a reconciliation process to determine what mapped elements actually changed from the previous render and only rerenders what is necessary. The React key is used when mapping arrays to help in this regard.
- If this is not the right way to do it. Please show me the right way to do it.
I shared the more common methods of mapping an array to JSX in point #1 above.
Upvotes: 1