Categories
React Bootstrap

React Bootstrap — Input Group Addons

React Bootstrap is one version of Bootstrap made for React.

It’s a set of React components that have Bootstrap styles.

In this article, we’ll look at how to add input groups to a React app with React Bootstrap.

Input Group Checkboxes and Radios

We can add checkboxes and radio buttons to input groups.

To do this, we can use the InputGrou.Checkbox and InputGroup.Radio components respectively.

For instance, we can write:

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import InputGroup from "react-bootstrap/InputGroup";
import FormControl from "react-bootstrap/FormControl";

export default function App() {
  return (
    <div>
      <InputGroup className="mb-3">
        <InputGroup.Prepend>
          <InputGroup.Checkbox/>
        </InputGroup.Prepend>
        <FormControl />
      </InputGroup>
      <InputGroup>
        <InputGroup.Prepend>
          <InputGroup.Radio />
        </InputGroup.Prepend>
        <FormControl />
      </InputGroup>
    </div>
  );
}

We just add them inside the InputGroup.Prepend component to add them to the left of the input box.

Multiple Inputs

We can have multiple controls in one input group.

We just add them all into the InputGroup .

For example, we can write:

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import InputGroup from "react-bootstrap/InputGroup";
import FormControl from "react-bootstrap/FormControl";

export default function App() {
  return (
    <div>
      <InputGroup className="mb-3">
        <InputGroup.Prepend>
          <InputGroup.Text>name and age</InputGroup.Text>
        </InputGroup.Prepend>
        <FormControl />
        <FormControl />
      </InputGroup>
    </div>
  );
}

Multiple Addons

Also, we can have multiple input group addons on either side of the input box.

For example, we can write:

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import InputGroup from "react-bootstrap/InputGroup";
import FormControl from "react-bootstrap/FormControl";

export default function App() {
  return (
    <div>
      <InputGroup className="mb-3">
        <InputGroup.Prepend>
          <InputGroup.Text>$</InputGroup.Text>
          <InputGroup.Text>US</InputGroup.Text>
          <InputGroup.Text>0.00</InputGroup.Text>
        </InputGroup.Prepend>
        <FormControl placeholder="amount" />
      </InputGroup>
      <InputGroup className="mb-3">
        <FormControl placeholder="amount" />
        <InputGroup.Append>
          <InputGroup.Text>$</InputGroup.Text>
          <InputGroup.Text>US</InputGroup.Text>
          <InputGroup.Text>0.00</InputGroup.Text>
        </InputGroup.Append>
      </InputGroup>
    </div>
  );
}

to add 3 addons on the left side of the first input group.

We add 3 addons to the right side of the second input group.

Button Addons

We can have buttons as add-ons.

For example, we can write:

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import InputGroup from "react-bootstrap/InputGroup";
import FormControl from "react-bootstrap/FormControl";
import Button from "react-bootstrap/Button";

export default function App() {
  return (
    <div>
      <InputGroup className="mb-3">
        <InputGroup.Prepend>
          <Button variant="outline-primary">click me</Button>
        </InputGroup.Prepend>
        <FormControl />
      </InputGroup>

      <InputGroup className="mb-3">
        <FormControl placeholder="username" />
        <InputGroup.Append>
          <Button variant="outline-primary">click me</Button>
        </InputGroup.Append>
      </InputGroup>

      <InputGroup className="mb-3">
        <InputGroup.Prepend>
          <Button variant="outline-primary">click me</Button>
          <Button variant="outline-primary">click me</Button>
        </InputGroup.Prepend>
        <FormControl />
      </InputGroup>

      <InputGroup>
        <FormControl placeholder="username" />
        <InputGroup.Append>
          <Button variant="outline-primary">click me</Button>
          <Button variant="outline-primary">click me</Button>
        </InputGroup.Append>
      </InputGroup>
    </div>
  );
}

We have buttons inside the InputGroup.Prepend and InputGroup.Append components to add them to the left and right of the input box respectively.

Buttons with Dropdowns

We can also add buttons with dropdowns as input addons.

For example, we can write:

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import InputGroup from "react-bootstrap/InputGroup";
import FormControl from "react-bootstrap/FormControl";
import Dropdown from "react-bootstrap/Dropdown";
import DropdownButton from "react-bootstrap/DropdownButton";

export default function App() {
  return (
    <div>
      <InputGroup className="mb-3">
        <DropdownButton
          as={InputGroup.Prepend}
          variant="outline-primary"
          title="Dropdown"
        >
          <Dropdown.Item href="#">foo</Dropdown.Item>
          <Dropdown.Item href="#">bar</Dropdown.Item>
          <Dropdown.Divider />
          <Dropdown.Item href="#">baz</Dropdown.Item>
        </DropdownButton>
        <FormControl />
      </InputGroup>

      <InputGroup>
        <FormControl placeholder="username" />

        <DropdownButton
          as={InputGroup.Prepend}
          variant="outline-primary"
          title="Dropdown"
        >
          <Dropdown.Item href="#">foo</Dropdown.Item>
          <Dropdown.Item href="#">bar</Dropdown.Item>
          <Dropdown.Divider />
          <Dropdown.Item href="#">baz</Dropdown.Item>
        </DropdownButton>
      </InputGroup>
    </div>
  );
}

We use the DropdownButton with the as prop set to InmputGeoup.Prepend so that it’ll fit into the input group.

Also, we set the variant to change the style of the button.

Conclusion

We can add dropdowns and buttons to input groups.

Also, we can have more than one input group addons in one group.

Categories
React Bootstrap

React Bootstrap — Images, Jumbotrons, and Figures

React Bootstrap is one version of Bootstrap made for React.

It’s a set of React components that have Bootstrap styles.

In this article, we’ll look at how to add images, figures, and jumbotrons to a React app with React Bootstrap.

Images

React Bootstrap has the Image component to let us add an image of various shapes.

We can have images that are rounded, a circle, or a thumbnail.

For example, we can write:

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import Image from "react-bootstrap/Image";

export default function App() {
  return (
    <div>
      <Image src="http://placekitten.com/200/200" rounded />
    </div>
  );
}

to add an image with a rounded corner with the rounded prop.

Likewise, we can add the roundedCircle prop to make the image display in a circle:

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import Image from "react-bootstrap/Image";

export default function App() {
  return (
    <div>
      <Image src="http://placekitten.com/200/200" roundedCircle />
    </div>
  );
}

We can also add the thumbnail prop to display them as thumbnails:

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import Image from "react-bootstrap/Image";

export default function App() {
  return (
    <div>
      <Image src="http://placekitten.com/200/200" thumbnail />
    </div>
  );
}

Fluid Images

We can use the fluid prop to scale images to the parent element’s width.

For instance, we can write:

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import Image from "react-bootstrap/Image";

export default function App() {
  return (
    <div>
      <Image src="http://placekitten.com/200/200" fluid />
    </div>
  );
}

to make the image scale to the parent’s width.

Figures

We can display a piece of content with the Figure component.

One good thing to display with it are images with a caption.

For instance, we can write:

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import Figure from "react-bootstrap/Figure";

export default function App() {
  return (
    <div>
      <Figure>
        <Figure.Image
          width={171}
          height={180}
          alt="171x180"
          src="http://placekitten.com/200/200"
        />
        <Figure.Caption>
          Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi
          efficitur massa tellus, non ultrices augue sagittis ornare. Sed
          ultrices ligula in est tempus tincidunt. Nam id consequat lacus, et
          mattis turpis. Sed velit nibh, tincidunt in ante a, accumsan fringilla
          odio. Etiam fermentum euismod enim id faucibus. Etiam facilisis nulla
          id leo imperdiet aliquet. In dignissim nulla non magna commodo
          ullamcorper. Fusce non ligula id tellus dapibus tempor sit amet in
          libero. Proin malesuada vulputate augue in bibendum. In mollis felis
          eu ante pharetra, ut vehicula sapien malesuada. Nulla imperdiet, urna
          a laoreet ullamcorper, massa nunc posuere neque, iaculis egestas urna
          arcu a metus.
        </Figure.Caption>
      </Figure>
    </div>
  );
}

We have the Figure component, which is a wrapper for the Figure.Image to display an image.

And we have the Figure.Caption component to display the caption below the image.

Jumbotron

A jumbotron is a lightweight and flexible component that can extend the whole viewport to show key content on our app.

For instance, we can write:

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import Jumbotron from "react-bootstrap/Jumbotron";
import Button from "react-bootstrap/Button";

export default function App() {
  return (
    <div>
      <Jumbotron>
        <h1>Title!</h1>
        <p>
          Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi
          efficitur massa tellus, non ultrices augue sagittis ornare. Sed
          ultrices ligula in est tempus tincidunt. Nam id consequat lacus, et
          mattis turpis. Sed velit nibh, tincidunt in ante a, accumsan fringilla
          odio. Etiam fermentum euismod enim id faucibus. Etiam facilisis nulla
          id leo imperdiet aliquet. In dignissim nulla non magna commodo
          ullamcorper. Fusce non ligula id tellus dapibus tempor sit amet in
          libero. Proin malesuada vulputate augue in bibendum. In mollis felis
          eu ante pharetra, ut vehicula sapien malesuada. Nulla imperdiet, urna
          a laoreet ullamcorper, massa nunc posuere neque, iaculis egestas urna
          arcu a metus.
        </p>
        <p>
          <Button variant="primary">Read more</Button>
        </p>
      </Jumbotron>
    </div>
  );
}

to show a jumbotron with a title and some body text.

At the bottom, we have a button.

We can make it scale with the parent with the fluid prop.

We write:

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import Jumbotron from "react-bootstrap/Jumbotron";
import Button from "react-bootstrap/Button";

export default function App() {
  return (
    <div>
      <Jumbotron fluid>
        <h1>Title!</h1>
        <p>
          Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi
          efficitur massa tellus, non ultrices augue sagittis ornare. Sed
          ultrices ligula in est tempus tincidunt. Nam id consequat lacus, et
          mattis turpis. Sed velit nibh, tincidunt in ante a, accumsan fringilla
          odio. Etiam fermentum euismod enim id faucibus. Etiam facilisis nulla
          id leo imperdiet aliquet. In dignissim nulla non magna commodo
          ullamcorper. Fusce non ligula id tellus dapibus tempor sit amet in
          libero. Proin malesuada vulputate augue in bibendum. In mollis felis
          eu ante pharetra, ut vehicula sapien malesuada. Nulla imperdiet, urna
          a laoreet ullamcorper, massa nunc posuere neque, iaculis egestas urna
          arcu a metus.
        </p>
        <p>
          <Button variant="primary">Read more</Button>
        </p>
      </Jumbotron>
    </div>
  );
}

to make it fluid.

Conclusion

React Bootstrap comes with the Image component to display images.

It also has the Figure and Jumbotron to let us display content in different ways.

Categories
React Bootstrap

React Bootstrap — Customizing Overlays

React Bootstrap is one version of Bootstrap made for React.

It’s a set of React components that have Bootstrap styles.

In this article, we’ll look at how to add overlays with React Bootstrap.

Disabled Elements

If we want to trigger overlays on a disabled element, we’ve to trigger the overlay from a wrapper element that isn’t disabled.

This is because disabled elements aren’t interactive.

For example, we can write:

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import Button from "react-bootstrap/Button";
import OverlayTrigger from "react-bootstrap/OverlayTrigger";
import Tooltip from "react-bootstrap/Tooltip";

export default function App() {
  return (
    <>
      <OverlayTrigger
        trigger="click"
        placement="right"
        overlay={<Tooltip id="tooltip-disabled">Tooltip!</Tooltip>}
      >
        <span className="d-inline-block">
          <Button disabled style={{ pointerEvents: "none" }}>
            Disabled button
          </Button>
        </span>
      </OverlayTrigger>
    </>
  );
}

We add the trigger and placement props so that we see the tooltip when we click on the disabled button.

This is possible because we have a span around the button, which lets us trigger the tooltip when the span is clicked.

Changing Containers

We can change the container to control the DOM element that the overlay is appended to.

For example, we can write:

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import Button from "react-bootstrap/Button";
import Overlay from "react-bootstrap/Overlay";
import Popover from "react-bootstrap/Popover";

export default function App() {
  const [show, setShow] = React.useState(false);
  const [target, setTarget] = React.useState(null);
  const ref = React.useRef(null);

  const handleClick = event => {
    setShow(!show);
    setTarget(event.target);
  };

  return (
    <div ref={ref}>
      <Button onClick={handleClick}>click me</Button>

      <Overlay
        show={show}
        target={target}
        placement="bottom"
        container={ref.current}
        containerPadding={20}
      >
        <Popover>
          <Popover.Title as="h1">Title</Popover.Title>
          <Popover.Content>
            Lorem ipsum dolor sit amet, consectetur adipiscing <b>elit</b>.
          </Popover.Content>
        </Popover>
      </Overlay>
    </div>
  );
}

to attach the popover to the div instead of the button.

we set the container to the ref of the div’s ref.

The rest of the code is the same as other popovers.

Updating Position Dynamically

The position of the popover can be updated dynamically.

For instance, we can write:

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import Button from "react-bootstrap/Button";
import OverlayTrigger from "react-bootstrap/OverlayTrigger";
import Popover from "react-bootstrap/Popover";

const UpdatingPopover = React.forwardRef(
  ({ popper, children, show: _, ...props }, ref) => {
    React.useEffect(() => {
      popper.scheduleUpdate();
    }, [children, popper]);

    return (
      <Popover ref={ref} content {...props}>
        {children}
      </Popover>
    );
  }
);

const longContent = `
  Lorem ipsum dolor sit amet,
  consectetur adipiscing elit.
  Cras ac urna bibendum, pretium magna id,
  imperdiet erat.
`;
const shortContent = "Lorem ipsum";

export default function App() {
  const [content, setContent] = React.useState(shortContent);

  React.useEffect(() => {
    const timerId = setInterval(() => {
      setContent(content === shortContent ? longContent : shortContent);
    }, 3000);

    return () => clearInterval(timerId);
  });

  return (
    <>
      <style type="text/css">
        {`
        .btn-primary {
          position: absolute;
          top: 50vh;
          left: 0vw;
        }
      `}
      </style>
      <OverlayTrigger
        trigger="click"
        overlay={<UpdatingPopover>{content}</UpdatingPopover>}
      >
        <Button>click me!</Button>
      </OverlayTrigger>
    </>
  );
}

to create a tooltip that changes text periodically.

We have th UpdatingPopover component that has the useEffect hook to watch for changes.

We call scheduleUpdate to update the popover.

We watch for changes for the children and popper props to make sure that we call scheduleUpdate when those changes.

We pass the ref and other props to the popover over so the position and other things can be applied.

children is the content of our tooltip.

In App , we have the OverlayTrigger with the text that changes periodically.

It’s triggered when we click on the button.

The content of the tooltip is set by setContent function in the useEffect callback.

Then function we return in there is for clearing the timer when we unmount the component.

Conclusion

We can make popovers dynamic.

Also, we can trigger overlays in disabled elements by adding a wrapper around them.

We can specify the container to attach the overlay to.

Categories
React Bootstrap

React Bootstrap — Customize Navbars

React Bootstrap is one version of Bootstrap made for React.

It’s a set of React components that have Bootstrap styles.

In this article, we’ll look at how to customize navbars to a React app with React Bootstrap.

Containers

We may wrap a navbar in the Container component to center it on a page.

For instance, we can write:

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import Navbar from "react-bootstrap/Navbar";
import Nav from "react-bootstrap/Nav";
import Container from "react-bootstrap/Container";

export default function App() {
  return (
    <>
      <Container>
        <Navbar bg="primary" variant="dark">
          <Navbar.Brand href="#home">Navbar</Navbar.Brand>
          <Nav className="mr-auto">
            <Nav.Link href="#home">Home</Nav.Link>
            <Nav.Link href="#foo">foo</Nav.Link>
            <Nav.Link href="#bar">bar</Nav.Link>
          </Nav>
        </Navbar>
      </Container>
    </>
  );
}

We center the navbar with the Container .

Placement

We can change the placement of the nav bar with the position utilities that comes with Bootstrap.

We pass in the fixed or sticky props to make the nav stick to the top or the bottom.

For example, we can write:

<Navbar fixed="top" />

to make the navbar stay fixed to the top.

And we can write:

<Navbar fixed="bottom" />

to make it fixed to the bottom.

We can replace fixed with sticky .

Fixed is displayed with respect to the viewport.

And sticky is positioned based on the user’s scroll position.

So we can write:

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import Navbar from "react-bootstrap/Navbar";
import Nav from "react-bootstrap/Nav";
import Container from "react-bootstrap/Container";

export default function App() {
  return (
    <>
      <Container>
        <Navbar fixed="top">
          <Navbar.Brand href="#home">Navbar</Navbar.Brand>
          <Nav className="mr-auto">
            <Nav.Link href="#home">Home</Nav.Link>
            <Nav.Link href="#foo">foo</Nav.Link>
            <Nav.Link href="#bar">bar</Nav.Link>
          </Nav>
        </Navbar>
      </Container>
    </>
  );
}

to make the navbar always stay on the top of the viewport.

Responsive Behaviors

To make the navbar responsive, we add the Navbar.Toggle and Navbar.Collkapse components to display the collapsed navbar as a menu when the screen is narrower than the given breakpoint.

For instance, we can write:

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import Navbar from "react-bootstrap/Navbar";
import Nav from "react-bootstrap/Nav";
import NavDropdown from "react-bootstrap/NavDropdown";

export default function App() {
  return (
    <>
      <Navbar collapseOnSelect expand="lg" bg="dark" variant="dark">
        <Navbar.Brand href="#home">App</Navbar.Brand>
        <Navbar.Toggle />
        <Navbar.Collapse>
          <Nav className="mr-auto">
            <Nav.Link href="#foo">foo</Nav.Link>
            <Nav.Link href="#bar">bar</Nav.Link>
            <NavDropdown title="Dropdown" id="collasible-nav-dropdown">
              <NavDropdown.Item href="#action/1">action 1</NavDropdown.Item>
              <NavDropdown.Item href="#action/2">action 2</NavDropdown.Item>
              <NavDropdown.Item href="#action/3">action 3</NavDropdown.Item>
              <NavDropdown.Divider />
              <NavDropdown.Item href="#action/4">action 4</NavDropdown.Item>
            </NavDropdown>
          </Nav>
          <Nav>
            <Nav.Link href="#baz">baz</Nav.Link>
            <Nav.Link eventKey={2} href="#qux">
              qux
            </Nav.Link>
          </Nav>
        </Navbar.Collapse>
      </Navbar>
    </>
  );
}

to create a navbar that’s collapsed into a hamburger menu when the screen is narrower than the lg breakpoint.

We have the Navbar.Toggle to display a toggle when the navbar is collapsed.

And Navbar.Collapse lets us display a collapsed navbar for narrow screens.

It’ll be expanded to the full navbar if the screen is within the lg breakpoint or higher.

Inside the Navbar.Collapse component, we have all the content for the navbar like the dropdown, links, and forms.

Navbar.Brand is displayed on the left side.

Conclusion

We can customize navbars with our own styling.

Also, we can make it responsive by adding a few components and props.

Categories
React Tips

React Tips — Context, Hover, and Input Fields

React is a popular library for creating web apps and mobile apps.

In this article, we’ll look at some tips for writing better React apps.

Get the Value of an Input Field Using React

To get the value of an input field with React, first, we set the inputted value to a state.

Then we get the latest value from the state.

For instance, we can write:

class InputForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      val: ''
    };
  }

  render() {
    return (
      //...
      <input value={this.state.val} onChange={evt => this.updateInputValue(evt)}/>
      //...
    );
  },

  updateInputValue(evt) {
    this.setState({
      val: evt.target.value
    });
  }
});

We created the updateInputValue method which calls setState to set the value of the input field as the value of the val state.

Then we pass that into the onChange prop.

The value prop has the this.state.val which we set.

With function components, we use the useState hook to set the value and retrieve it.

For instance, we can write:

import { useState } from 'react';

function InputForm() {
  const [val, setVal] = useState('');

  return (
    <div>
      <input value={val} onInput={e => setVal(e.target.value)}/>
    </div>
  );
}

We called the useState function with the initial value of the input.

Then we passed a function to the onInput prop to run it to set the value to the val state when whenever something is entered.

Then we get the latest inputted value with the val variable.

Pass Form Element State to Sibling or Parent Elements

To most versatile way to pass data between element is to us the context APU.

For instance, we can write:

import React, { useState, useContext } from "react";
import ReactDOM from "react-dom";

const Context = React.createContext(null);

const initialAppState = {};

function App() {
  const [appState, updateAppState] = useState(initialAppState);

return (
    <div>
      <Context.Provider value={{ appState, updateAppState }}>
        <Comment />
      </Context.Provider>
    </div>
  );
}

function Comment() {
  const { appState, updateAppState } = useContext(Context);

  function handleCommentChange(e) {
    updateAppState({ ...appState, comment: e.target.value });
  }

  return (
    <div className="book">
      <input
        type="text"
        value={appState.comment}
        onChange={handleCommentChange}
      />
      <br />
      <div>
        <pre>{JSON.stringify(appState, null, 2)}</pre>
      </div>
    </div>
  );
}

We created the context with the React.createContext method to create the context.

Then in App, we add the Context.Provider so that all the child elements can have access to the context.

Then we created the Comment component which calls the useContext hook to use our Context context. In the component, we have an input to change the appState as we enter something. This will be reflected in all components that use the context.

We can see what we entered in the stringified JSON that’s below the input.

How to Implement a:hover with Inline CSS Styles in React

We can listen to the mouseenter and mouseleave events to create an effect for hover.

For instance, we can write:

class Foo extends React.Component {
  constructor() {
    this.state = { hover: false };
  }

  toggleHover(){
    this.setState({ hover: !this.state.hover })
  },

  render() {
    let linkStyle;
    if (this.state.hover) {
      linkStyle = { backgroundColor: 'red' }
    } else {
      linkStyle = { backgroundColor: 'green' }
    }
    return(
      <div>
        <a style={linkStyle} onMouseEnter={this.toggleHover} onMouseLeave={this.toggleHover}>Link</a>
      </div>
    )
  }
}

We created our component by adding a a element that listens to the mouseenter and mouseleave events by passing methods to the onMpuseEnter and onMouseLeave props.

The toggleHover method toggles the hover state between true and false .

Then in the render method, we set the backgroundColor property depending on the truth value of the hover state.

Also, we can use the style-it library which lets us embed CSS with pseudoclasses into our React components.

We install it by running:

npm install style-it --save

Then we can write:

import React from 'react';
import Style from 'style-it';

class Foo  extends React.Component {
  render() {
    return Style.it(`
      p:hover {
        color: red;
      }
    `,
      <p>hover me</p>
    );
  }
}

Then we use the Style.it tag from the style-it library to let us set the hover state of our element.

We can also use the Style component to do the same thing.

For instance, we can write:

import React from 'react';
import Style from 'style-it';

class Foo extends React.Component {
  render() {
    return (
      <Style>
        {`
          p:hover {
            color: red;
          }
        `}
        <p>hover me</p>
      </Style>
    );
  }
}

We use the Style component and embed our CSS with the hover pseudoclass in the string.

Then we’ll see a color change when we hover over the p element.

Conclusion

We can use a library or plain JavaScript to create a hover effect.

There are various ways to get input field values and pass data around multiple components.