11 January 2020

Reusable button components in React



  • Add Button.js file and add below code

import React from "react";
const Button = props => {
return (
<button onClick={props.handleClick} className={"btn-" + props.theme}>
{props.children}
</button>
);
};
export default Button;

  • Add ClassEXP1.js file and added below code
import React, { Component } from "react";
import Button from "./Button";

class ClassEXP1 extends Component {
constructor() {
super();
this.state = { Data: "" };
}
submitClick = e => {
console.log("Submit Button Clicked");
this.setState({ Data: "Submit Button Clicked" });
};
resetClick = e => {
console.log("Reset Button Clicked");
this.setState({ Data: "Reset Button Clicked" });
};
cancelClick = e => {
console.log("Cancel Button Clicked");
this.setState({ Data: "Cancel Button Clicked" });
};
render() {
return (
<div>
<Button theme="green" handleClick={this.submitClick}>
Submit
</Button>
<Button theme="blue" handleClick={this.resetClick}>
Reset
</Button>
<Button theme="red" handleClick={this.cancelClick}>
Cancel
</Button>
<div>{this.state.Data}</div>
</div>
);
}
}
export default ClassEXP1;
  • Add styles.css file and add below code
.App {
font-family: sans-serif;
text-align: center;
}
button {
padding: 10px 10px;
border-radius: 15px;
font-size: 18px;
font-weight: 600;
margin: 0 5px;
}
.btn-red {
background-color: #e14d4d;
color: #d9abab;
}
.btn-green {
background-color: green;
color: #e0a2d2;
}
.btn-blue {
background-color: blue;
color: #4e6f64;
}
.container {
border: 2px solid red;
padding: 10px;
}
  • Update index.js file as below.
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
import ClassEXP1 from "./ClassEXP1";

function App() {
return (
<div className="App">
<ClassEXP1 />
</div>
);
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);


Output:
 Click on Submit button
Click on Reset button

No comments:

Post a Comment