DEV Community

Mehul Lakhanpal
Mehul Lakhanpal

Posted on • Originally published at codedrops.tech

React: Create an 'EmptyState' component

Empty states and values are always checked. It throws an error if the array is undefined or null. There has to be a message if there is no data.

I made this EmptyState component which covers these basic use cases.

/** EmptyState.js */
import React from "react";
import _ from "lodash";
import styled from "styled-components";

const StyledContainer = styled.div`
  text-align: center;
  width: 100%;
  font-size: 2rem;
  color: lightgrey;
`;

const EmptyState = ({ input, children }) => {
  // matches falsy values as well as empty arrays & objects
  const isEmpty = _.isEmpty(input);

  return isEmpty ? <StyledContainer>Empty</StyledContainer> : children;
};

export default EmptyState;
Enter fullscreen mode Exit fullscreen mode

Usage:

/** App.js */
import React from "react";
import EmptyState from "./EmptyState";

const App = ({ data }) => {
  return (
    <EmptyState input={data}>
      {data.map((name) => (
        <h3>{name}</h3>
      ))}
    </EmptyState>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

Comment down what additions you think could be made.


Thanks for reading 💙

Follow @codedrops.tech for more.

InstagramTwitterFacebook

Micro-Learning ● Web Development ● Javascript ● MERN stack

codedrops.tech


Projects

File Ops - A VS Code extension to easily tag/alias files & quick switch between files

Top comments (0)