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.
CodePudding user response:
The prop 'onCLick' does not exist in your Button component, that's why it does not work. Change your Button.js
export default ({ name = "Add Button", event }) => (
<button onClick={event}>{name}</button>
);
by
export default ({ name = "Add Button", onClick }) => (
<button onClick={onClick}>{name}</button>
);
Now you ca use your Button with onClick instead of event. Then in your App Component
export default function App() {
const [buttonsOnCanvas, setButtonsOnCanvas] = useState([]);
function handleAddButtonClick() {
setButtonsOnCanvas([...buttonsOnCanvas, <Button />]);
}
return (
<div className="App">
<Button
onClick={handleAddButtonClick} // Better avoid anonymous function
/>
<div className="canvas">{buttonsOnCanvas}</div>
</div>
);
}