Skip to content

Instantly share code, notes, and snippets.

@masahitojp
Created June 3, 2019 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save masahitojp/ec630dbdb4cb8180141a711f02dc2ce6 to your computer and use it in GitHub Desktop.
Save masahitojp/ec630dbdb4cb8180141a711f02dc2ce6 to your computer and use it in GitHub Desktop.
test
// Template Tree
global.templateIDsByPath = global.templateIDsByPath || {
'404': undefined
}
// Get template for given path
const getComponentForPath = path => {
path = cleanPath(path)
return global.componentsByTemplateID[global.templateIDsByPath[path]]
}
global.reactStaticGetComponentForPath = getComponentForPath
global.reactStaticRegisterTemplateIDForPath = (path, id) => {
global.templateIDsByPath[path] = id
}
export default class Routes extends Component {
render () {
const { component: Comp, render, children } = this.props
const getFullComponentForPath = path => {
let Comp = getComponentForPath(path)
let is404 = path === '404'
if (!Comp) {
is404 = true
Comp = getComponentForPath('404')
}
return newProps => (
Comp
? <Comp {...newProps} {...(is404 ? {is404: true} : {})} />
: null
)
}
const renderProps = {
componentsByTemplateID: global.componentsByTemplateID,
templateIDsByPath: global.templateIDsByPath,
getComponentForPath: getFullComponentForPath
}
if (Comp) {
return (
<Comp
{...renderProps}
/>
)
}
if (render || children) {
return (render || children)(renderProps)
}
// This is the default auto-routing renderer
return (
<Route path='*' render={props => {
let Comp = getFullComponentForPath(props.location.pathname)
// If Comp is used as a component here, it triggers React to re-mount the entire
// component tree underneath during reconciliation, losing all internal state.
// By unwrapping it here we keep the real, static component exposed directly to React.
return Comp && Comp({ ...props, key: props.location.pathname })
}} />
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment