19

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>
    );
  }
}
0

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Does react support any kind of element tag as long as it's loaded?
@MaximusS it supports any HTML tag or a React component.
That's where I got confused. If an external library called maximus.js provided a widget named maximus, would React understand <maximus width="600" />?
By "widget" do you mean a React Component?
That link at the end is gold
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.