Last active
April 5, 2022 20:21
-
-
Save notpeelz/a5336b0d02aa634f03bcd70ee12c484d to your computer and use it in GitHub Desktop.
react-router conditional rendering using negative route matching
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
import PropTypes from 'prop-types' | |
import { Route, Switch } from 'react-router-dom' | |
const generateRouteId = (() => { | |
let i = 0 | |
return (name) => { | |
return `${name}-${i}` | |
} | |
})() | |
export default class RenderCondition extends React.Component { | |
static propTypes = { | |
children: PropTypes.oneOfType([ | |
PropTypes.arrayOf(PropTypes.node), | |
PropTypes.node | |
]).isRequired, | |
exclude: PropTypes.array.isRequired, | |
substitute: PropTypes.node, | |
} | |
static defaultProps = { | |
substitute: null, | |
} | |
render() { | |
const {exclude, substitute, children} = this.props | |
return ( | |
<Switch> | |
{exclude.map((path) => ( | |
<Route key={generateRouteId('exclude-route-')} | |
path={path} | |
component={substitute} /> | |
))} | |
<Route children={children} /> | |
</Switch> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment