Categories
React Answers

How to get the value of checkbox using a ref in React?

Sometimes, we want to get the value of checkbox using a ref in React.

In this article, we’ll look at how to get the value of checkbox using a ref in React.

How to get the value of checkbox using a ref in React?

To get the value of checkbox using a ref in React, we can use the checked property of the checkbox.

For instance, we write:

import React, { useRef } from "react";

export default function App() {
  const checkboxRef = useRef();

  const save = () => {
    console.log(checkboxRef.current.checked);
  };

  return (
    <div>
      <div>
        <label>
          <input type="checkbox" ref={checkboxRef} /> Check me out
        </label>
      </div>
      <button onClick={save}>Submit</button>
    </div>
  );
}

We create the checkboxRef with the useRef hook.

Then we assign the ref prop to checkboxRef to assign the checkbox as the value of checkboxRef.current.

Next, we define the save function to logged the checked value of the checkbox, which is stored in checkboxRef.current.checked.

Finally, we assign the onClick prop of the button to the save function to run it when we click it.

Therefore, when we check or uncheck the checkbox and click Submit, we should see the checked value logged.

Conclusion

To get the value of checkbox using a ref in React, we can use the checked property of the checkbox.

Categories
React Answers

How to fix ‘Static HTML elements with event handlers require a role.’ warning in React?

Sometimes, we want to fix ‘Static HTML elements with event handlers require a role.’ warning in React.

In this article, we’ll look at how to fix ‘Static HTML elements with event handlers require a role.’ warning in React.

How to fix ‘Static HTML elements with event handlers require a role.’ warning in React?

To fix ‘Static HTML elements with event handlers require a role.’ warning in React, we should set the role attribute of the a element.

For instance, we write:

import React from "react";

export default function App() {
  return (
    <div>
      <a role="button" onClick={() => alert("hello")}>
        hello
      </a>
    </div>
  );
}

to set the role attribute of the a element to button.

Conclusion

To fix ‘Static HTML elements with event handlers require a role.’ warning in React, we should set the role attribute of the a element.

Categories
React Answers

How to make a scrollable div to stick to bottom, when outer div changes in size in React?

Sometimes, we want to make a scrollable div to stick to bottom, when outer div changes in size in React.

In this article, we’ll look at how to make a scrollable div to stick to bottom, when outer div changes in size in React.

How to make a scrollable div to stick to bottom, when outer div changes in size in React?

To make a scrollable div to stick to bottom, when outer div changes in size in React, we can use flexbox.

For instance, we write:

import React from "react";

export default function App() {
  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        height: "300px"
      }}
    >
      <div style={{ flexGrow: 0 }}>foo</div>
      <div
        style={{
          flexGrow: 1,
          overflowY: "auto",
          alignItems: "center",
          display: "flex"
        }}
      >
        bar
      </div>
      <div style={{ flexGrow: 0 }}>baz</div>
      <div></div>
    </div>
  );
}

We make a flex container by setting the display CSS property to 'flex', flexDirection to 'column' and a height for the flex container.

Then we add the elements inside the flex container.

We make the bottom div stick to bottom by setting flexGrow of the div above the bottom one to 1 to make it fill the space.

And we set flexGrow of the bottom div to 0 so that it won’t stretch.

Conclusion

To make a scrollable div to stick to bottom, when outer div changes in size in React, we can use flexbox.

Categories
React Answers

How to fix the Redux store does not have a valid reducer error in React?

Sometimes, we want to fix the Redux store does not have a valid reducer error in React.

In this article, we’ll look at how to fix the Redux store does not have a valid reducer error in React.

How to fix the Redux store does not have a valid reducer error in React?

To fix the Redux store does not have a valid reducer error in React, we can call combineReducer with an object that has the state property name as keys and the corresponding reducer as the values.

For instance, we write:

import React from "react";
import { Provider, useDispatch, useSelector } from "react-redux";
import { combineReducers, createStore } from "redux";

const CountReducer = (state = 0, action) => {
  switch (action.type) {
    case "ADD":
      return state + 1;
    default:
      return state;
  }
};

const rootReducer = combineReducers({
  count: CountReducer
});

const store = createStore(rootReducer);

const Counter = () => {
  const count = useSelector((s) => s.count);
  const dispatch = useDispatch();

  return (
    <div>
      <button onClick={() => dispatch({ type: "ADD" })}>+</button>
      <span>{count}</span>
    </div>
  );
};

export default function App() {
  return (
    <Provider store={store}>
      <Counter />
    </Provider>
  );
}

We have the CountReducer reducer function that returns the state + 1 if the 'ADD' action type is dispatched.

Then we call combineReducers with an object with the count as the state property name and the CounterReducer as its reducer.

Next, we call createStore with rootReducer to create the store from the root reducer.

Then we create the Counter component that calls the useSelector hook to return the the value of the count state.

And we call the useDispatch hook to return the dispatch function that we can use to dispatch actions.

Finally, in App, we wrap Provider around Counter so useSelector and useDispatch can be used in Counter.

And we set the store prop to the store so we can dispatch actions and get states from the store.

Conclusion

To fix the Redux store does not have a valid reducer error in React, we can call combineReducer with an object that has the state property name as keys and the corresponding reducer as the values.

Categories
React Answers

How to add export to CSV button in a React table?

Sometimes, we want to add export to CSV button in a React table.

In this article, we’ll look at how to add export to CSV button in a React table.

How to add export to CSV button in a React table?

To add export to CSV button in a React table, we can use the react-csv library.

To install it, we run:

npm i react-csv

Then we add the button to the table by writing:

import React from "react";
import { useTable } from "react-table";
import { CSVLink } from "react-csv";

const csvData = [
  { firstName: "John", lastName: "Doe" },
  { firstName: "Jane", lastName: "Doe" }
];

const Table = ({ columns, data }) => {
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow
  } = useTable({
    columns,
    data
  });

  return (
    <table {...getTableProps()}>
      <thead>
        {headerGroups.map((headerGroup) => (
          <tr {...headerGroup.getHeaderGroupProps()}>
            {headerGroup.headers.map((column) => (
              <th {...column.getHeaderProps()}>{column.render("Header")}</th>
            ))}
          </tr>
        ))}
      </thead>
      <tbody {...getTableBodyProps()}>
        {rows.map((row, i) => {
          prepareRow(row);
          return (
            <tr {...row.getRowProps()}>
              {row.cells.map((cell) => {
                return <td {...cell.getCellProps()}>{cell.render("Cell")}</td>;
              })}
            </tr>
          );
        })}
      </tbody>
    </table>
  );
};

export default function App() {
  const columns = React.useMemo(
    () => [
      {
        Header: "Name",
        columns: [
          {
            Header: "First Name",
            accessor: "firstName"
          },
          {
            Header: "Last Name",
            accessor: "lastName"
          }
        ]
      }
    ],
    []
  );

  const data = React.useMemo(() => {
    return csvData.map((d) => Object.values(d));
  }, []);

  return (
    <>
      <CSVLink data={data}>Download me</CSVLink>
      <Table columns={columns} data={csvData} />;
    </>
  );
}

We create the Table component which calls the useTable hook with the columns and data props to return an object that has the properties we use to create the table.

Next, we add a CSV download link by using the CSVLink component.

We pass in a nested array as the value of the data prop so react-csv can generate the CSV from it.

We create the nested array by calling useMemo with a callback that returns the nested array which we create by calling csvData.map with a callback that returns the values in an array from each csvData entry with Object.values.

Now we should see a Download me button which we can click to download the CSV.

Conclusion

To add export to CSV button in a React table, we can use the react-csv library.