React, Bootstrap and and simple check-boxes
It is possible to easily make a bootstrap-styled React application using the react-bootstrap module. This module provides react components that have the boostrap styling.
In the example below I show how to build a very simple example application which presents bootstrap checkboxes and shows how to monitor their state through the React state and props concepts.
The key concepts are as follows:
- Changes of the state of checkboxes are monitored by providing the onChange prop with a separate partially applied function. This provides easy connection back to which exact check box has been clicked on
- The change of state of the checbox is then recorded in the App component state
- The monitoring of checkboxes is implemented by passing this part of App to state to a simple display component as a prop
This is the main code and there is a link to CodeSandbox at the bottom to try this out!
// (C) Bojan Nikolic 2019
// Licensed under BSD-3 license
// Example of using and monitoring check-boxes in react-bootstrap
import React, { Component } from "react";
import Container from "react-bootstrap/Container";
import Form from "react-bootstrap/Form";
const cboxes = [ "check1", "check2" ];
// This renders the status of each checkbox
class CheckMonitor extends Component {
renderLine(k) {
return (
<p key={k}> check {k} is {this.props.check[k] ? ' true ' : 'false'} </p>
);
}
render() {
return (
<Container>
{cboxes.map(this.renderLine.bind(this))}
</Container>
);
}
}
// The app consists of check-boxes and a compnent that renders
// depending on the value of the check-boxes
class App extends Component {
constructor(props) {
super(props);
this.state = {
check: {}
};
}
handleChange(key, event) {
let s=this.state.check;
s[key]=event.target.checked;
this.setState({check: s});
}
// Renders all of the check-boxes
renderChecks() {
return cboxes.map(
k =>
<Form.Check
type='checkbox'
label={k}
onChange={this.handleChange.bind(this, k)}
key={k}
/> );
}
render() {
return (
<Container>
<h1 className="header">Example</h1>
{this.renderChecks() }
<CheckMonitor
check={this.state.check}
/>
</Container>
);
}
}
export default App;