I'm trying to store in an empty array a user input and a unique id as an object.
So I have:
const [weight, setWeight] = useState([]);
that I want to fill with this function:
const submitWeight = () => {
setWeight([{ value: inputWeight, id: uuidv4() }, ...weight]); // this one.
setDefaultMessageWeight("");
closedClass();
};
Any ideas? Thank you!
Here is an example of how you can access a rendered input element using ref inside your component.
import { useRef, useState } from "react";
export default function App() {
const [weight, setWeight] = useState([]);
const inputRef = useRef(null);
const submitWeight = () => {
let inputWeight = inputRef.current.value;
setWeight([{ value: inputWeight, id: uuidv4() }, ...weight]);
// ...
};
return (
<div>
<input ref={inputRef} />
<button onClick={submitWeight}>Submit</button>
{weight.map(({ value }, index) => (
<p>
Weight #{index} is {value}
</p>
))}
</div>
);
}