I am very new to React and Front End development.
I recently came across something that confused me.
Why would the following code fragment work properly:
import React, { useState } from "react";
import "./styles.css";
import Button from "./Button";
export default function App() {
const [buttonsOnCanvas, setButtonsOnCanvas] = useState([]);
return (
<div className="App">
<Button
event={() => {
setButtonsOnCanvas([...buttonsOnCanvas, <Button />]);
}}
/>
<div className="canvas">{buttonsOnCanvas}</div>
</div>
);
}
but not this:
import React, { useState } from "react";
import "./styles.css";
import Button from "./Button";
export default function App() {
const [buttonsOnCanvas, setButtonsOnCanvas] = useState([]);
function handleAddButtonClick() {
setButtonsOnCanvas([...buttonsOnCanvas, <Button />]);
}
return (
<div className="App">
<Button
onClick={() => handleAddButtonClick()}
/>
<div className="canvas">{buttonsOnCanvas}</div>
</div>
);
}
Code for Button.js: import React from "react";
export default ({ name = "Add Button", event }) => (
<button onClick={event}>{name}</button>
);
The difference appears to be in onClick vs event attributes. In the event version, clicking on the initial button instantiated within the web browser will constantly add new button instances. With onClick, nothing happens.
Via Active questions tagged javascript - Stack Overflow https://ift.tt/NuzpWm1
Comments
Post a Comment