I am working on a react button component that receives 1 function as prop to be executed on the onClick event
<Button onClick={() => console.log('hello')}>
this passes as
<button onClick={onClick}>
Say hello
</button>
A new requirement has come, and we need to make a ping to our server to see how many users actually click on the button, but not every button will share this behaviour, what would be a clean way to add a new property and if it is present, execute both functions on click
<Button
onClick={() => console.log('hello')}
track=true
/>
<button
onClick={() =>{
if track trackClick()
onClick()
}}>
Say hello
</button>
Shift everything into the parent component. Have a state that logs the counts of the buttons, and have your handleClick function call the first function and then, depending on the track information, update the count. Button1, in this example, will call doThing first and then update the count; Button2 will only call the function, and not update the count.
const { useEffect, useState } = React;
function Example() {
const [ count, setCount ] = useState(0);
useEffect(() => console.log(count), [count]);
function doThing() {
console.log('Thing');
}
function handleClick(e) {
const { track } = e.target.dataset;
doThing();
if (track === 'true') setCount(count + 1);
}
return (
<div>
<Button
handleClick={handleClick}
text="Button1"
track={true}
/>
<Button
handleClick={handleClick}
text="Button2"
track={false}
/>
</div>
);
}
function Button({ handleClick, text, track }) {
return (
<button
onClick={handleClick}
data-track={track}
>{text}
</button>
);
}
ReactDOM.render(
<Example />,
document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>