To demonstrate my question, I'll compare vanilla javascript and react. In javascript, when I have
<div>
<button >1</button>
<button >2</button>
<button >3</button>
<button >4</button>
<button >5</button>
</div>
and I want to add some functionality to all buttons, I can do
const buttons = document.querySelectorAll(".btn");
buttons.forEach(btn=>{
btn.addEventListener("click",(e)=>{
//some code here
})
})
In react, how can I do the same thing, instead of adding "onClick" to every single button? Because imagine if there are 20 buttons like this:
<button className="btn" onClick={()=>{
//some code here
}}>button</button>
I could still use querySelector like the javascript way, but I heard that is a bad practice in react. So I wonder if there is any other way that can make the code cleaner.
CodePudding user response:
React is perfect for this, because it allows you to reuse components! You could make a component that contains your click handler, then reuse it throughout your application.
const MyReusableButton = () => {
const myClickHandler = () => {
console.log("Clicked!");
}
return <button onClick = {myClickHandler}>Click Me</button>;
}
const App = () => {
// now I can reuse my button component as many times as I want!
return (
<div>
<MyReusableButton />
<MyReusableButton />
<MyReusableButton />
<MyReusableButton />
</div>
);
}
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>
CodePudding user response:
Make a list that describes whatever is unique about your buttons. Map the list into your buttons.
const nums = [0,1,2,3,4,5]
return <div>
{nums.map(num =>
<button onClick={() => console.info("clicked" num)}>
This is button {num}
</button>
)}
</div>
CodePudding user response:
Use a loop to create an array of JSX objects and render them. This is an example from an earlier project I was working on.
let grid = []
maze.forEach((row, i) => {
let renderedRow = []
row.forEach((block, j) => {
renderedRow.push(<Block key={size.width * i j}
inheritedType={block}
dimensions={defaultDimensions * scale}
onAction={() => {
setBlock(i, j)
setMazeFuture([])
}}
onDoubleClick={() => updateMaze(i, j, "empty")}
isDown = {isDown}
setIsDown={setIsDown}
appendToHistory={appendCurrentMazeToHistory}
/>)
})
grid.push(<Row key={i} columns={renderedRow} rowHeight={defaultDimensions * scale}/>)
})
return (
{grid}
)