Skip to content
Advertisement

Using a regular JavaScript library inside a React component

I’m curious what’s the best way to use a regular JavaScript library (not written as a React component) inside a React environment.

For example, let’s say there’s a JavaScript library that embeds a simple widget to my webpage. The instructions are as follows:

  1. Include the loading tag in the header.
  2. Embed the snippet anywhere you want.

In a normal webpage, I would do the following:

<head>
    <script src="http://karaoke.com/source.js"></script>
</head>

<body>
    <h1>Hello look at my cool widget library</h1>
    <karaoke width="600" height="400" />
</body>

How do I achieve the same effect where I have a React component like this?

class MainView extends Component {
  render() {
    return (
      <div>
        <h1>I want to show my karaoke widget here, but how?</h1>
      </div>
    );
  }
}

Advertisement

Answer

The main purpose of JSX is to feel like HTML. The main purpose of render in a React component is to render that “fake” (virtual) HTML. If your external widget is also a React component, the solution is straightforward:

class MainView extends Component {
  render() {
    return (
      <div>
        <h1>Hello look at my cool widget library</h1>
        <Widget width="600" height="400" />
      </div>
    );
  }
}

All you have to make sure is that the code above runs after your widget script is loaded (so the Widget component is present). The exact solution to this would depend on your build system.

If your external library is not a React component, then you cannot use a custom widget tag and you must render actual HTML.

The big trick is to not return from render but manually render ourselves after the widget initializes what it needs:

class MainView extends Component {
  render() {
    // don't render anything
    return <div/>;
  },

  componentDidMount() {
    // find the DOM node for this component
    const node = ReactDOM.findDOMNode(this);

    // widget does stuff
    $(node).activateMyCoolWidget();

    // start a new React render tree with widget node
    ReactDOM.render(<div>{this.props.children}</div>, node);
  }
});

Take a look at portals for more details.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement