Situation -
Initial number input in text field - 1
List of Items -
- 1
- 6
- 11
Upon removing 1 from the text field, the list becomes -
New List Items -
- NaN
- NaN
- NaN
Now, if you input 4 in the field.
The updated List Items are -
- NaN
- NaN
- 4
- 9
- 14
Expected Outcome -
The List should only show - 4, 9 and 14
, not NaN, NaN, 4, 9, 14
.
Please advise on what might be incorrect here.
Code Section -
import React, { useState } from "react";
import List from "./List";
const ReRendering = () => {
const [number, setNumber] = useState(1);
const getList = () => [number, number + 5, number + 10];
return (
<div>
<input
type="number"
value={number}
onChange={(e) => setNumber(parseInt(e.target.value, 10))}
/>
<div>
<List getList={getList} />
</div>
</div>
);
};
export default ReRendering;
List.js File
import { useEffect, useState } from "react";
const List = ({ getList }) => {
const [item, setItem] = useState([]);
useEffect(() => {
setItem(getList());
}, [getList]);
return (
<div className="list">
{item.map((x) => (
<div key={x}>{x}</div>
))}
</div>
);
};
export default List;
Live Demo - https://codesandbox.io/s/gallant-gagarin-l18ni1?file=/src/ReRendering.js:0-463