I'm new to react, wanted to ask if this piece of code is good practice, because I have a feeling I'm doing something wrong but not sure what.
I have a main class component which has an array of packages which consists of width, height etc.
I'm passing this packages array as props to another functional component where I want to update these values. Currently my implementation looks like this:
<Card pck={pck} key={pck.packageId}/>
export default function Card(props) {
const widthProperties = useState(0);
props.pck.width = widthProperties[0]
const setWidth = widthProperties[1];
<input type="number" id={props.pck.packageId} className="form-control"
value={props.pck.width}
onChange={(e) => setWidth(parseInt(e.target.value))}
placeholder="Width" required/>
}
It works correctly, but as I said, I believe that I'm not using the useState
with props
correctly. Could someone explain what is wrong here? Because 3 lines of code to update props' state looks strange for me.
const [width, setWidth] = useState(0);
should be in the parent and passed down to the children like<Card width={width} setWidth={setWidth} key={pck.packageId}/>
, then used in the Card like<input value={props.width} onChange={props.setWidth} />
.<Card />
component. So how would that look then?this.state.packages.map(pck => <Card width={pck.width} ? />
How would thesetWidth
function look like? If i have my packages in classes state object.setWidth
will probably take an id as argument so you can find the package you want to modify. You will have something likesetWidth = (width, packageId) => { this.setState({ packages: this.state.packages.map(pck => pck.id == packageId ? { ...pck, width } : pck) }) }
.pck.packageId == packageId
. Are you sure you passing a correctpackageId
tosetWidth
? You can add aconsole.log(width, packageId)
insidesetWidth
to see what's going on.