Level: expert • Mithril.js Version: latest
3rd-party component dom lifecycle m.mount oncreate react
This examples shows how to integrate React components into a Mithril.js application.
Type | Name | URL |
---|---|---|
script | mithril@latest | https://unpkg.com/mithril@latest |
script | react/umd/react.development.js | https://unpkg.com/react/umd/react.development.js |
script | react-dom/umd/react-dom.development.js | https://unpkg.com/react-dom/umd/react-dom.development.js |
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.
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.