Skip to content

Instantly share code, notes, and snippets.

@notpeelz
Last active April 5, 2022 20:21
Show Gist options
  • Save notpeelz/a5336b0d02aa634f03bcd70ee12c484d to your computer and use it in GitHub Desktop.
Save notpeelz/a5336b0d02aa634f03bcd70ee12c484d to your computer and use it in GitHub Desktop.
react-router conditional rendering using negative route matching
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