React Integration

by barneycarroll

Level: expert • Mithril.js Version: latest

This examples shows how to integrate React components into a Mithril.js application.

Live Example

Dependencies

,,
Type Name URL
scriptmithril@latesthttps://unpkg.com/mithril@latest
scriptreact/umd/react.development.jshttps://unpkg.com/react/umd/react.development.js
scriptreact-dom/umd/react-dom.development.jshttps://unpkg.com/react-dom/umd/react-dom.development.js

JavaScript

class ReactComponent extends React.Component {
  constructor(){
    super()

    this.state = { count : 0 }
  }

  render(){
    return [
      <p key="0">
        Count: {this.state.count}
      </p>,

      <button key="1" onClick={() => {
        this.setState({count: this.state.count + 1})
      }}>
        Increment
      </button>
    ]
  }
}

const MithrilComponent = () => {
  let showSubComponent = false

  return {
    view: () => [
      m('label',
        m('input[type=checkbox]', {
          onchange: e => {
            showSubComponent = e.target.checked
          }
        }),

        'Render React component?'
      ),

      m('br'),

      showSubComponent &&
        m('.ReactBridge', {
          oncreate: v => {
            ReactDOM.render(<ReactComponent/>, v.dom)
          },
        })
    ]
  }
}

m.mount(document.body, MithrilComponent)

The snippet is using the most current version of Mithril.js framework. It is aimed at expert users who are familiar with all of the aspects of the framework and JavaScript itself.

In addition to the Mithril.js hyperscript function m(), here we can see an example of Mithril.js' m.mount API method. It also shows, how Mithril.js' lifecycle methods can be used. This can be seen here by using the oncreate hook.

The example was contributed by barneycarroll and last modified on 26 October 2021. Click here to see more examples contributed by the author.

Contribute

If anyone has some improvements, that should be addressed, let me know by opening an issue. Or simply fork the repository on GitHub, push your commits and send a pull request. For starting your work, you can click the edit link below. Thanks for contributing.

See more code examples  •  Edit this example on GitHub