When I press a button both buttons are turn on. I just want open the button I pressed. How can i do it?
2 Answers
You can use id for each button. Example here:
import React, { Component, Fragment } from "react";
import Data from "./parameters.json";
import { Table } from "react-bootstrap";
class Parameter extends Component {
container = React.createRef();
state = {
open: null,
handleOpen: false,
selectedOptions: []
};
handleButtonClick = (e) => {
const id = parseInt(e.target?.id);
if (this.state.open && this.state.open !== id)
return;
this.setState((state) => {
return {
open: state.open !== 0 && !state.open ? id : null
};
});
};
handleChange = (selectedOptions) => {
this.setState({ selectedOptions });
};
render() {
const uniqueTags = [];
Data.map((img) => {
if (uniqueTags.indexOf(img.groupName) === -1) {
uniqueTags.push(img.groupName);
}
});
return (
<div>
<Table style={{ width: "100%" }}>
<thead>
<tr>
<th>Parameter Name</th>
</tr>
</thead>
<tbody>
{uniqueTags.map((value, index) => {
return (
<Fragment>
<tr>
<button
type="button"
className="button"
onClick={this.handleButtonClick}
id={index}
>
<div id={index} style={{ marginLeft: "30px" }}>
<td id={index}>▼{value}</td>
</div>
</button>
</tr>
{this.state.open === index &&
Data.map(
(item) =>
item.zeroBasedEnumeration !== "0" &&
item.groupName === value && (
<tr>
<td style={{ paddingLeft: "80px" }}>
{item.objectName}
</td>
</tr>
)
)}
</Fragment>
);
})}
</tbody>
</Table>
</div>
);
}
}
export default Parameter;
Comments
You are using the same open state for every button rendered.
One possible solution I can think of by analyzing your code is that you can create an openButtonKeyState and map those with the unique identifier of each button, which, in that case, can be objectName. Then on the onClick handler, add or remove the key to this array.