Skip to content

Instantly share code, notes, and snippets.

@pavermakov
Created June 29, 2023 11:11
Show Gist options
  • Save pavermakov/13e0f62bf83aab1198fd499f7be44732 to your computer and use it in GitHub Desktop.
Save pavermakov/13e0f62bf83aab1198fd499f7be44732 to your computer and use it in GitHub Desktop.
Conditional rendering in React
import React from "react";
import PropTypes from "prop-types";
const Then = ({ children }) => children;
Then.propTypes = {
children: PropTypes.node.isRequired
};
const If = ({ condition, children }) => {
const childrenArray = React.Children.toArray(children);
const thenComponent = childrenArray.find((child) => child.type.name === Then.name);
const elseComponent = childrenArray.find((child) => child.type.name === Else.name);
const elseIfComponents = childrenArray.filter((child) => child.type.name === ElseIf.name);
if (condition) {
return thenComponent ? thenComponent.props.children : children;
}
const elseIfResults = elseIfComponents.map((elseIfComponent) => elseIfComponent.props.condition);
if (elseIfResults.every((result) => !result)) {
return elseComponent ? elseComponent.props.children : null;
}
const firstTrueElseIf = elseIfComponents.find((elseIfComponent, index) => elseIfResults[index]);
if (firstTrueElseIf) {
return firstTrueElseIf.props.children;
}
return null;
};
If.propTypes = {
condition: PropTypes.bool.isRequired,
children: PropTypes.node.isRequired
};
const Else = ({ children }) => children;
Else.propTypes = {
children: PropTypes.node.isRequired
};
const ElseIf = ({ condition, children }) => {
if (condition) {
return children;
}
return null;
};
ElseIf.propTypes = {
condition: PropTypes.bool.isRequired,
children: PropTypes.node.isRequired
};
export { If, Then, Else, ElseIf };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment