Learning React Bootstrap
- Part 1: Installing and Configuring
- Part 2: Grid System Components
- Part 3: Common Components
- Part 4: Reacting to Events
React Bootstrap is a redesign of the popular Bootstrap front-end framework for use in React projects.
Reacting to Events
Components like <Alert> expose an onClose property for working with state changes within the component. When a user clicks on the closing element in an <Alert>, for example, a function passed to the component will be called. This allows for “reacting” to events within the component through using functions like setState() to track state changes in a class and change what is rendered as a result.
import React from 'react';
import {Container, Row, Col, Alert} from 'react-bootstrap';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
showAlert: true
};
}
render() {
const alert = <Alert variant="danger" onClose={() => this.setState({showAlert: false})} dismissible>
<Alert.Heading>Alert heading</Alert.Heading>
<p>
Alert content.
</p>
</Alert>;
if(this.state.showAlert) {
return (
<Container>
<Row>
<Col>
{alert}
</Col>
</Row>
</Container>
);
} else {
return (
<Container>
<Row>
<Col>
</Col>
</Row>
</Container>
);
}
}
}
export default App;
In a function example, and using the React hook useState() function, the same presentation can be achieved using React state tracking outside of any particular class components as well.
import React, {useState} from 'react';
import {Container, Row, Col, Alert} from 'react-bootstrap';
function App() {
const [show, setShow] = useState(true);
if(show) {
return(
<Container>
<Row>
<Col>
<Alert variant="danger" onClose={() => setShow(false)} dismissible>
<Alert.Heading>Alert heading</Alert.Heading>
<p>
Alert content.
</p>
</Alert>
</Col>
</Row>
</Container>
);
} else {
return (
<Container>
<Row>
<Col>
</Col>
</Row>
</Container>
);
}
}
export default App;