Categories
JavaScript React

Using React-Datepicker with Bootstrap

We can use react-datepicker with Bootstrap easily.

We should either use Reactstrap or React Bootstrap to add Bootstrap to our app.

In this article, we’ll use React Bootstrap with react-datepicker.

First, we install both by running:

npm install react-bootstrap bootstrap react-datepicker

Bootstrap is required by React-Bootstrap. react-datepicker is also installed.

Then we can use both of them together by writing:

import React, { useState } from "react";
import DatePicker from "react-datepicker";

import "react-datepicker/dist/react-datepicker.css";
import { Container, Row, Col } from "react-bootstrap";

export default function App() {
  const [startDate, setStartDate] = useState(new Date());
  return (
    <div className="App">
      <Container fluid>
        <Row>
          <Col>
            <DatePicker
              selected={startDate}
              onChange={date => setStartDate(date)}
            />
            <p>{startDate.toString()}</p>
          </Col>
        </Row>
      </Container>
    </div>
  );
}

We imported the Container, Row, and Col components from React Bootstrap.

These are components for a container to hold other elements. fluid makes it responsive.

Inside Col, we have DatePicker component from react-datepicker.

Also, we imported the CSS file that comes with react-datepicker so that the date picker is displayed with proper styles.

We have the selected prop that’s set to the startDate state.

onChange is set to a function that calls setStartDate to set the state.

Then we see an input box that shows a date picker when we click on it.

When we click a date, then the date that’s selected is displayed below the input box.

useState has new Date() as its argument, so its initial value will be the current date and time.

So when we first load the page, the current date will be selected on the date picker.

react-datepicker and Bootstrap can be used together. We just have to use React derives of Bootstrap like React Bootstrap or Reactstrap.

Categories
JavaScript React

Create Good Looking Charts with the React Chartkick NPM Package

To create charts in React apps, wd can use the React Chartkick NPM package.

We can get started easily.

Create Charts

We run the following commands to install the packages we need:

yarn add react-chartkick chart.js

Chart.js is a dependency required for React Chartkick, so we have to install it.

Then we can create our chart as follows:

import React from "react";
import { LineChart } from "react-chartkick";
import "chart.js";

const data = { "2020-01-01": 11, "2020-01-02": 6, "2020-01-03": 10 };
export default function App() {
  return (
    <div className="App">
      <LineChart data={data} />
    </div>
  );
}

We just create an object with the x-axis labels as the keys and the corresponding values for the y-axis.

Once we did that, we get:

https://thewebdev.info/wp-content/uploads/2020/05/linechart.png

To create a bar chart, we can write:

import React from "react";
import { BarChart } from "react-chartkick";
import "chart.js";

const data = [["eat", 32], ["drink", 100]];
export default function App() {
  return (
    <div className="App">
      <BarChart data={data} />
    </div>
  );
}

The data structure and component to import are different, but we can create one without much effort.

Once we wrote the code above, we get:

https://thewebdev.info/wp-content/uploads/2020/05/barchart.png

The React Chartkick package support many other kinds of charts like pie charts, area charts, geo charts, and more.

Options

We can customize the options of the charts to suit our needs.

For instance, we can set the min and max values for the x-axis.

We can use the xmin and xmax props as follows:

import React from "react";
import { LineChart } from "react-chartkick";
import "chart.js";

const data = { "2020-01-01": 11, "2020-01-02": 6, "2020-01-03": 10 };

export default function App() {
  return (
    <div className="App">
      <LineChart data={data} xmin="2020-01-01" xmax="2020-01-03" />
    </div>
  );
}

We make sure that our data matches the x-axis ranges.

Likewise, we can set the range for the y-axis by writing:

import React from "react";
import { LineChart } from "react-chartkick";
import "chart.js";

const data = { "2020-01-01": 11, "2020-01-02": 6, "2020-01-03": 10 };

export default function App() {
  return (
    <div className="App">
      <LineChart
        data={data}
        min={0}
        max={20}
        xmin="2020-01-01"
        xmax="2020-01-03"
      />
    </div>
  );
}

To change the color of the line, we can use the colors prop:

import React from "react";
import { LineChart } from "react-chartkick";
import "chart.js";

const data = { "2020-01-01": 11, "2020-01-02": 6, "2020-01-03": 10 };

export default function App() {
  return (
    <div className="App">
      <LineChart data={data} colors={["green"]} />
    </div>
  );
}

We just pass in an array to change the line color.

One we wrote our code, we get:

https://thewebdev.info/wp-content/uploads/2020/05/green.png

Labels and Legends

The React Chartkick NPM package provides with props to enable a legend.

We set the legend prop to true to display a legend.

Then we use the label prop to add text to the legend.

To set the titles for the x and y axes, we can use the xtitle and ytitle props respectively.

For instance, we can write:

import React from "react";
import { LineChart } from "react-chartkick";
import "chart.js";

const data = { "2020-01-01": 11, "2020-01-02": 6, "2020-01-03": 10 };

export default function App() {
  return (
    <div className="App">
      <LineChart
        data={data}
        label="Population"
        legend={true}
        xtitle="Time"
        ytitle="Population"
      />
    </div>
  );
}

Once we did that, we get:

https://thewebdev.info/wp-content/uploads/2020/05/labels.png

The React Chartkick NPM package has chart components that take many more props to let us create charts.

It’s one of the easiest libraries for us to create charts in React apps.

Categories
JavaScript React

Set the Default Checked Value of a React Radio Button

To create a radio button group with React and set the default checked value of it, we have to set the value to the state that we want.

Then we’ve to set the checked prop to be the expression to compare the value of the radio button with the currently selected value.

This way, React will check the right one.

We also need an onChange handler to update the state to the right value.

To do all that, we write:

import React, { useState } from "react";

const fruits = ["orange", "apple", "grape"];

export default function App() {
  const [fruit, setFruit] = useState("apple");
  return (
    <div className="App">
      {fruits.map(f => (
        <>
          <input
            type="radio"
            name="fruit"
            value={f}
            checked={fruit === f}
            onChange={e => setFruit(e.currentTarget.value)}
          />{" "}
          {f}
        </>
      ))}
      <p>{fruit}</p>
    </div>
  );
}

We have the fruits array, which we use to map the values to radio buttons.

Radio buttons are input elements with type 'radio'.

The name attribute also have to be set to the same name so that we know that they’re in the same group.

The value attribute is set to the fruit state, so that we can update the checked value by comparison fruit with the value of the value attribute of the radio button.

We have:

onChange={e => setFruit(e.currentTarget.value)}

which gets the e.currentTarget.value property, which has the currently checked radio buttons’ value and set it as the value of the fruit state.

This will update the radio button when we click on it.

Then we display the value of the radio button that’s checked below so that we can see what we actually selected.

To set the default value, we just set the initial value of the fruit state since we used that as the value of the value prop.

The button that’s clicked should have the same value that’s displayed.

To set the default value of a React radio button element, we just have to set the value prop to the state value that we want.

Categories
JavaScript React

Set a Default Value for a React Select Element

We can set the default value of a React select element by using the useState hook.

The default value can be set as the default value of the hook. Then we can set it as the value of the value prop of the select element.

For instance, we can write:

import React, { useState } from "react";

const fruits = ["orange", "apple", "grape"];

export default function App() {
  const [fruit, setFruit] = useState("apple");
  return (
    <div className="App">
      <select
        value={fruit}
        onChange={e => setFruit(fruits[e.target.selectedIndex])}
      >
        {fruits.map(f => (
          <option value={f}>{f}</option>
        ))}
      </select>
      <p>{fruit}</p>
    </div>
  );
}

We set the value prop to fruit so that we set the initial value of it.

We map the fruits entries to the option elements.

Then we add an onChange handler to call setFruit as we change selection.

We get the selected value from the fruits array by writing:

fruits[e.target.selectedIndex]

so that we get the string given the index of the selected option.

Then we display the selected value so that we can see what we selected below the select element.

Since we set the initial value of the fruit state to 'apple', that’s what we display when we load the select element, which means that it’s the default value.

Now we can have default values for our React select elements.

Categories
JavaScript React

React – How to Get Form Values on Submit

To get form values on submit, we can pass in an event handler function into the onSubmit prop to get the inputted form values.

To do that, we write:

import React from "react";

export default function App() {
  const [name, setName] = React.useState("");
  const handleSubmit = e => {
    e.preventDefault();
    console.log(name);
  };
  return (
    <div className="App">
      <form onSubmit={handleSubmit}>
        <input
          typ="text"
          value={name}
          onChange={e => setName(e.target.value)}
        />
        <br />
        <input type="submit" />
      </form>
    </div>
  );
}

We use the useState hook so that we can use the phone state as the value of the value prop.

The onChange prop has a function that calls setName returned by the useState prop to set the value of name with it.

Then we can enter something and see what we entered.

Then we defined the handleSubmit function, which takes an event object e as a parameter.

We’ve to call e.preventDefault to prevent the default server-side submit behavior.

Then we log the value of name to show the value of it in the console.

Now when we enter something and press the Submit button, we’ll see the value of what we entered logged in the console.

With React, getting form values on submit isn’t hard to do. We just have to pass an event handler function to the onSubmit that takes an event object parameter.

Then inside it, we call preventDefault and then we can get the inputted form field data from the state as long as we set the inputted value to a state variable with the onChange handler.