Skip to content

Instantly share code, notes, and snippets.

@dlagg
Created July 23, 2020 09:53
Show Gist options
  • Save dlagg/55c604dafc450536c3538a6816d87dde to your computer and use it in GitHub Desktop.
Save dlagg/55c604dafc450536c3538a6816d87dde to your computer and use it in GitHub Desktop.
React Class Component Example
<div id="root"></div>

React Class Component Example

This component is a React.Component in the Class structure, and includes some of the basic scaffolding for that, like a constructor with date, and a click handler for a form element that changes state.

A Pen by CodePen on CodePen.

License.

// to do... proptypes? error handling?
class Card extends React.Component {
constructor(props) {
super(props)
this.state = {
darkMode: true
}
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({ darkMode: !this.state.darkMode });
}
componentWillMount() {
// could do something like pull state from API
}
componentDidMount() {
}
componentWillUnmount() {
}
componentDidUpdate() {
}
render() {
const { title } = this.props;
let modeClass = this.state.darkMode ? "dark-mode" : "light-mode";
let checked = this.state.darkMode ? "checked" : "unchecked";
return <div className={`box content ${modeClass}`}>
<h1>{title}</h1>
<p>I was built with a Class component extending React.Component.</p>
<label className="checkbox">
<input
type="checkbox"
defaultChecked={checked}
onChange={this.handleChange} />
{' '}Dark Mode
</label>
</div>;
}
}
const el = document.querySelector("#root");
ReactDOM.render(<Card title='Example Component' />, el);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.7.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.7.0/umd/react-dom.production.min.js"></script>
body {
height: 100vh;
margin: 0;
display: grid;
place-items: center;
}
.box {
width: 300px;
h1 {
font-size: 20px;
}
&.dark-mode {
background: black;
color: #bbb;
h1 {
color: white;
}
.checkbox:hover {
color: white;
}
}
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.2/css/bulma.min.css" rel="stylesheet" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment