How would you integrate react with non-react code?

Category
Reddit
Author
Joi KozeyJoi Kozey

In the last few years, React as a JavaScript framework for front-end web and mobile applications has risen. Developers use it to build engaging, user-friendly interface features in web applications and websites. It is used to easily add new in-demand features to an existing project that needs to be modified to cater to a new need that suddenly arises. Integrating React with non-React code can be challenging but is possible.

Below are several steps and strategies to integrate React components into a project that also uses non-React (vanilla JavaScript, jQuery, etc.) code without a complete overhaul of the existing environments.

Establish a JavaScript Environment

Configure an environment that allows the utilization of JSX syntax, enables the division of your code into modules using import/export syntax, and permits the use of packages (such as React) from the npm package registry. Such an environment should allow you to write React components as individual files instead of a single file.

Integrating JSX-based React components with non-React code involves transpiling the JSX to JavaScript and then integrating the transpiled component using various strategies like mounting to DOM elements or using custom elements. Proper loading order and communication between the components are also crucial for successful integration. If the code you need to integrate is split into files, try to use it in divs, and if it throws errors, try code transpiling.

Component Rendering

Position and render your React components at the desired locations on the page. The exact approach depends on your existing page setup. When integrating React with non-React code, you need to establish communication between them. Custom Events, Callbacks, or a State Management library can synchronize state or pass data between React and non-React parts of your application. Below are the man ways to render components:

  1. You can create custom elements (Web Components) using React components and then use them in your non-React code. This approach is useful when using React components in projects that use plain HTML, CSS, JavaScript, or other libraries/frameworks.
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>React with Non-React</title>
    </head>
    <body>
    
    <div id="root"></div> <!-- React Component will be mounted here -->
    
    <!-- Include React and ReactDOM from CDN -->
    <script src="https://unpkg.com/react@17/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
    
    <!-- Include Babel for in-browser JSX transpilation -->
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    
    <!-- Write JSX code and transpile it in the browser -->
    <script type="text/babel">
      class MyComponent extends React.Component {
        render() {
          return <div>Hello from JSX!</div>;
        }
      }
    
      // Mount the React component to the div with id 'root'
      ReactDOM.render(<MyComponent />, document.getElementById('root'));
    </script>
    
    <!-- Non-React JavaScript code -->
    <script>
      document.addEventListener('DOMContentLoaded', function() {
        const div = document.createElement('div');
        div.textContent = 'Hello from Vanilla Javascript!';
        document.body.appendChild(div);
      });
    </script>
    
    </body>
    </html>
  2. If your existing project uses jQuery or another JavaScript library, you can integrate React components by mounting them to specific DOM elements created or manipulated by those libraries.
    class MyReactComponent extends React.Component { render() { return <div>Hello from React!</div>; } } $(document).ready(function () { const $container = $('#react-container'); if ($container.length > 0) { ReactDOM.render(<MyReactComponent />, $container[0]); } });
  3. When integrating React with non-React code, you might have situations where you need to render React components in specific places in the DOM that are outside the current React application’s root. React portals are extremely useful in such cases, as they allow you to render React components virtually anywhere in the DOM tree, facilitating smoother integration with non-React parts of your application, like rendering inside elements managed by jQuery or other libraries.
    import React from 'react';
    import ReactDOM from 'react-dom';
    
    class Modal extends React.Component {
      constructor(props) {
        super(props);
        // Create a div that will hold the Portal content
        this.el = document.createElement('div');
      }
    
      componentDidMount() {
        // Append the created div to the body when the component mounts
        document.body.appendChild(this.el);
      }
    
      componentWillUnmount() {
        // Remove the created div from the body when the component unmounts
        document.body.removeChild(this.el);
      }
    
      render() {
        // Use ReactDOM.createPortal to render the children of this component
        // into the created div, effectively rendering it outside the parent component's DOM node.
        return ReactDOM.createPortal(
          this.props.children,
          this.el
        );
      }
    }
    
    // Usage of Modal component
    function App() {
      return (
        <div>
          <h1>Hello, World!</h1>
          <Modal>
            <div style={{backgroundColor: 'white', padding: '20px', border: '1px solid black'}}>
              I am a modal!
            </div>
          </Modal>
        </div>
      );
    }
    
    export default App;

Best Practices when Integrating React with Non-React Code

When integrating React into a non-React codebase, it’s crucial to follow best practices to ensure a smooth integration, maintainability, and performance. Here are several best practices to think about

1. Incremental Adoption

If you are working on a large codebase, consider incrementally adopting React by replacing parts of your application one at a time. You can start by replacing smaller, isolated parts of your UI with React components and gradually move to more complex parts as you become more comfortable with React.

2. Consistent state management

Make sure that the state is synchronized between React and non-React parts to avoid inconsistencies in the UI and whenever possible, avoid duplicating the state between React and non-React code. Establish efficient communication between React and non-React components using callbacks, custom events, or a global event bus and avoid tight coupling between React and non-React code to make future upgrades or replacements easier. While maintaining a consistent state, always optimize code for performance.

3. Error handling and reporting

Be careful not to make the React components break the whole application. Write effective unit test and integration tests to ensure it is evident what parts are breaking. Follow consistent coding standards and practices in both React and non-React code while clearly documenting how the React and non-React parts of the application interact.

4. Separation of Concerns

Clearly define the interactions between React and non-React code, such as using props and custom events for communication while keeping React and non-React code as decoupled as possible to maintain modularity. Consider how the planned upgrades to the system are configured to ensure this decoupled characteristic of the code is maintained.

Conclusion

In conclusion, integrating React into non-React codebases can be challenging, but following best practices like starting small, maintaining clear boundaries, optimizing for performance, and planning for future upgrades can help in achieving successful and maintainable integration.