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.
Try 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;
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;
Comment down what additions you think could be made.