I have a React app with a component that has a button to add a list of dynamic buttons. Each dynamic button has the onClick method to fire a function (sendOption) with an id parameter. The problem is, the function "sendOption" is not firing after clicking on the added button.
I also changed this:
<button onClick={this.sendOption(buttonId)}>
to this:
<button onClick={() => this.sendOption(buttonId)}>
but still, the onClick is not working. How can I solve this?
Component:
let buttonId = 0;
Class ButtonCreation extends Component {
constructor(props) {
super(props);
this.state = {
buttonsList: [],
}
}
addButton = () => {
buttonId += 1;
this.setState({
buttonsList: [...this.state.buttonsList, <button onClick={this.sendOption(buttonId)}>Send Option</button>]
})
}
sendOption = (buttonId) => {
console.log(buttonId)
}
render() {
return(
<div>
<button onClick={this.addButton}>Add new Button</button>
{this.state.buttonsList}
</div>
);
}
}
export default ButtonCreation;
The issue is with click event binding:
Change this:
onClick={this.sendOption(buttonId)}
To:
onClick={() => this.sendOption(buttonId)}
NOTE:
on button click, it will not print right id with that button, but prints last
buttonId
always, I have also solved that issue.Another issue with you code is when the user clicks on any, with this:
<button value={buttonId} onClick={(e) => this.sendOption(e.target.value)}>Send Option</button>
You can run the code snippet and check:
let buttonId = 0; class App extends React.Component { constructor(props) { super(props); this.state = { buttonsList: [] } } addButton = () => { buttonId += 1; this.setState({ buttonsList: [...this.state.buttonsList, <button value={buttonId} onClick={(e) => this.sendOption(e.target.value)}>Send Option</button>] }) } sendOption = (buttonId) => { console.log(buttonId) } render() { return( <div> <button onClick={this.addButton}>Add Button </button> <br/><br/> {this.state.buttonsList} </div> ); } } ReactDOM.render(<App />, document.getElementById('react-root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="react-root"></div>
Try this:
import React from "react";
import "./styles.css";
let buttonId = 0;
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
buttonsList: []
};
}
addButton = () => {
buttonId += 1;
this.setState({
buttonsList: [
...this.state.buttonsList,
<button id={buttonId} onClick={(e) => this.sendOption(e)}>Send Option</button>
]
});
};
sendOption = e => {
console.log(e.target.id);
};
render() {
return (
<div>
<button onClick={this.addButton}>Add new Button</button>
{this.state.buttonsList}
</div>
);
}
}
code pen: https://codesandbox.io/s/clever-flower-7fm05?file=/src/App.js
here is an example for each button with each id:
use target.id for getting each button ID by click use key for avoiding DOM key Problem
let buttonId = 0;
export default function App() {
const [buttonsList, setbuttonsList] = useState([]);
const addButton = () => {
buttonId += 1;
setbuttonsList(prevState => [
...prevState,
<button
key={buttonId}
id={buttonId}
onClick={event => sendOption(event, event.target.id)}
>
Send Option
</button>
]);
};
const sendOption = (event, id) => {
console.log(id);
};
return (
<div>
<button onClick={addButton}>Add new Button</button>
{buttonsList}
</div>
);
}
code [ https://codesandbox.io/s/vigorous-firefly-c7nrc?fontsize=14&hidenavigation=1&theme=dark]
Your problem is almost solved by @Vivek.
But there are few points that I wanted to suggest you in your code. You will get better idea by looking at the following code snippet:
class App extends React.Component { constructor(props) { super(props); this.state = { buttonsList: [], btnCounter: 0, } } addButton = () => { // you can pass name, value for new button based on some value // you can also generate new id every time: const id = new Date().getTime(); // use functional setState whenever update previous state this.setState((prevState) => ({ btnCounter: prevState.btnCounter + 1, buttonsList: [...prevState.buttonsList, { id: prevState.btnCounter + 1, name: `Name${prevState.btnCounter + 1}`, value: `Send Option` }] })); // if possible add properties of button instead of directly adding element into state } sendOption = (buttonId) => { console.log(buttonId) } render() { const { buttonsList } = this.state; return ( <div> <button onClick={this.addButton}>Add new Button</button> {buttonsList && buttonsList.length > 0 && buttonsList.map((btn, i) => ( <div key={btn.id}> <button name={btn.name} onClick={() => this.sendOption(btn.id)} > {btn.value} </button> </div> ))} </div> ); } } ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div>
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.