· 1 min read

Super Simple Router for React Without Any Dependencies

An abstract illustration to accompany an article titled “Super Simple Router for React Without Any Dependencies”. The...

Here is some very simple code to render React components dynamically without using a framework or routing library.

It doesn't cover pushState and URL parsing, so in that sense it isn't a routing library.

But it does let you render components from other components in a simple way.


const Goodbye = () => {
  return (
    <button onClick={() => render(<Hello />)}>
      I don't know why you say "Goodbye", I say "Hello, hello, hello".
    </button>
  )
}

const Hello = () => {
  return (
    <button onClick={() => render(<Goodbye />)}>
      You say "Goodbye" and I say "Hello, hello, hello".
    </button>
  )
}

const render = (component) => {
  const event = new Event('render')
  event.component = component
  document.dispatchEvent(event)
}

document.addEventListener('render', (event) => {
  ReactDOM.render(
    event.component,
    document.getElementById('root')
  )
})

render(<Hello />)

Here is a JSFiddle for it https://jsfiddle.net/L2yq8sjx/2/

Comments

Leave a comment