Hello I am trying to pass state up from a form to my useState
hook in the parent component but nothing happens when I submit my form. The aim is to create a visual of a box on the screen when the user inputs height width and color.
form code:
const NewBoxForm = (props) => {
const [height, setHeight] = useState();
const [width, setWidth] = useState();
const [color, setColor] = useState("");
const handleChange = (event) => {
const {value, name } = event.target;
let change = name === "height" ? setHeight(value) : name === "width" ? setWidth(value) :
setColor(value);
};
const handleSubmit = (event) => {
event.preventDefault();
props.createBox(height, width, color);
};
return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="height">Height</label>
<input name="height" id="height"type="text" onChange={handleChange} value=
{height}>
</input>
<label htmlFor="width">Width</label>
<input name="width" id="width" type="text"onChange={handleChange} value={width}>
</input>
<label htmlFor="color">Color</label>
<input name="color" id="color"type="text" onChange={handleChange} value={color}>
</input>
</div>
<button>Submit</button>
</form>
);
};
I am passing the input from my form via a prop props.createBox
to a function create
which should update my useState
state boxes
but it doesn't. When I console.log
newBox
it only returns the height
... can anyone see why?
const BoxList = () => {
const [boxes, setBoxes] = useState([{height: 0, width:0, color:""}]);
const boxesArray = boxes.map((box) => {
return(
<Box width={box.height}
height={box.width}
color={box.color}
/>
)
});
const create = (newBox) => {
console.log(newBox)
setBoxes(boxes => [...boxes, newBox])
};
return (
<div>
<NewBoxForm createBox={create} />
{boxesArray}
</div>
);
};
const create = (height, width, color) => {
let newBox = {height: height, width: width, color: color};
console.log(newBox);
setBoxes(boxes => [...boxes, newBox])
};
You're sending three separate variables in your handleSubmit call instead of one object.
const handleSubmit = (event) => {
event.preventDefault();
props.createBox(height, width, color);
};
should be:
const handleSubmit = (event) => {
event.preventDefault();
props.createBox({height, width, color});
};
console.log is only logging the height because that is the first parameter you're sending.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.