Learning React Bootstrap: Part 4: Reacting to Events

Learning React Bootstrap

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;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.