Frontend recipes React elements

The preferred way to inject JavaScript into web apps is using [React] as custom elements using Remount. For instance, we may integrate a dynamic user profile component built with JavaScript as a custom element. Your HTML markup would look like so:

<x-user-profile json-props='{"email":"[email protected]"}'></x-user-profile>

We can then implement this as a React component:

class UserProfile extends React.Component {
  state = {}

  componentDidMount() {
    // This will be called when <x-user-profile> first appears.
    fetch(this.props.email).then(data => {
      this.setState({ data })
    })
  }

  render() {
    const { data } = this.state

    // This markup will appear inside the <x-user-profile> element.
    if (!data) {
      return <span>Loading...</span>
    } else {
      return <div>Full name: {data.fullname}</div>
    }
  }
}

Using Remount, we can wire the UserProfile component to appear on <x-user-profile> elements.

import { define } from 'remount'

define({
  'x-user-profile': UserProfile
})

For more information on this, see the Remount documentation.

Where to define remount()

It's preferred to define all your custom elements en masse. This can be kept in your main entry point (eg, app.js), or a file included from it (eg, initializers/elements.js).

import { define } from 'remount'
import { UserProfile, UserTooltip, AvatarImage } from './components'

define({
  'x-user-profile': UserProfile,
  'x-user-tooltip': UserTooltip,
  'x-avatar-image': AvatarImage
})

See also

  • remount - Mount React components as custom elements
  • rsjs - Reasonable Structure for JavaScript