Reputation: 312
I am new to React. I have 3 buttons which are imported as a Component into App.js as:
import Button from "./Button";
I want to add an onClick function to these Components as:
<div className="buttonsdiv">
<Button text="+" / onClick = {...}>
//text is a parameter defined in Button.js
<Button text="RESET" onClick = {...} />
<Button text="-"onClick = {...} />
</div>
Is there a way to do it?
Upvotes: 1
Views: 5334
Reputation: 6336
If it's a functional component, try this:
JavaScript
const add = (e) => { }
const sub = (e) => { }
const reset = (e) => { }
JSX
<div className="buttonsdiv">
<Button text="+" onclick={add} />
<Button text="RESET" onclick={reset} />
<Button text="-" onclick={sub} />
</div>
If it's a component without state, pass the functions to the component, like this:
const component = (props) => {
return {
<div className="buttonsdiv">
<Button text="+" onclick={props.add} />
<Button text="RESET" onclick={props.reset} />
<Button text="-" onclick={props.sub} />
</div>
}
}
Upvotes: 0
Reputation: 4613
As @BrianThompson said, it's all about the implementation of your Button
component. The idea is to pass the onClick
prop to the rendered html element, i.e.:
const Button = (props) => {
return (
<button onClick={props.onClick}/>
);
}
Upvotes: 3