Reputation: 185
I made a component for one Button with animation effect so that i can use it in my other components by simply importing it. I did a lot of code in Button component for animation so i don't want to use a lot of same code again and again in other components.
Is there any way I can use the Button for different events by just importing. For example; In one component I import the Button as submitting the user information and in other component i am import the Button for displaying user data.
Upvotes: 0
Views: 660
Reputation: 3420
Of course there is, just give it different props:
Example on codesandbox:
https://codesandbox.io/s/admiring-wing-okiqw
The parent:
function App() {
return (
<div className="App">
<h1>Hi there</h1>
<h2>Click on first button to sum 1, click to second button to sum 2!</h2>
<Fbutton functionality="sumone" />
<Fbutton functionality="sumtwo" />
</div>
);
}
You are calling Fbutton
two times, one with sumone
another with sumtwo
props.
The son:
function Fbutton(props) {
const [count, setCount] = useState(0);
const sumone = () => setCount(count + 1);
const sumtwo = () => setCount(count + 2);
return (
<div>
<button onClick={props.functionality === "sumone" ? sumone : sumtwo}>
Sum: {count}
</button>
</div>
);
}
Upvotes: 1
Reputation: 793
Create a props for button to provide an option like
Implement in other component:
<custombutton mode={"submitmode"} clickevent={handleBtnClick} />
<custombutton mode={"displaymode"} clickevent={handleBtnClick} />
handleBtnClick=() =>{
if(mode =="submitmode"){
//..do code for submit
}
else if(mode=="displaymode"){
//..do code for display
}
}
Actual button component:
class Button extends custombutton{
handleClick =() =>{
this.props.clickevent();
}
render(){
return(
{props.mode=="submitmode" &&
<button type="submit" onClick={handleClick} class="submitstyle" />
}
{props.mode=="displaymode" &&
<button class="displaystyle" onClick={handleClick} />
}
);
}
}
Upvotes: 1
Reputation: 1831
Of course! This is the components idea. You mught want to receive a prop in your Button to handle whatever happens onClick.
I.E.
Parent Component create the especific function to handle
function handleClick() { ... }
<YourCustomButton onClick={handleClick} />
In YourCustomButton just use this function on event
class YourCustomButton extends React......
<Button onClick={this.props.onClick}> ...
Upvotes: 2
Reputation: 12235
suppose you have a button like <Button pageName="home" />
And in that component suppose ,
class Button extends Compoenent {
onClick =()=>{
if(this.props.pageName == "home"){
// do your home action
} else if(this.props.pageName == "tab"){
// do your tab action
}
}
render(){
return(
<Button onClick={() => this.onClick()} />
)
}
}
Hope thats clear, feel free for doubts
Upvotes: 0