Languages
[Edit]
EN

React - how to use pure JavaScript components

0 points
Created by:
Dirask Community
6240

In this article, we would like to show you how to use pure JavaScript components in React.

In the below example we create VanillaJSModal pure JavaScript component and wrap it with ReactModal so we can use it later in our React application.

To do so, we have used a combination of React hooks:

  • useMemo -┬áwas used to create our component only once,
  • useEffect:
    • with an empty array of dependencies ([]) -┬áto hide the modal┬áif the┬áReact component is destroyed,
    • with visible┬áor┬ámessage property - to┬ámonitor these poperty┬ávalues.

Runnable example:

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines while working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

function VanillaJSModal() {
  var modal = null;
  var message = null;
  this.showModal = function(text) {
    if (modal) {
      return;
    }
    modal = document.createElement('div');
    modal.style.cssText = '' +
      'position: fixed;' +
      'left: 0; top: 0; right: 0; bottom: 0;' +
      'background: rgba(181, 237, 194, 0.2);' +
      'display: flex;' +
      'z-index: 1000;';
    message = document.createElement('div');
    message.style.cssText = '' +
      'margin: auto;' +
      'font-size: 20px;' +
      'color: black;';
    message.innerText = text || 'Message not set ...';
    modal.appendChild(message);
    document.body.appendChild(modal);
  };
  this.hideModal = function() {
    if (modal) {
      document.body.removeChild(modal);
      modal = null;
    }
  };
  this.changeMessage = function(text) {
    if (message) {
      message.innerText = text || '';
    }
  };
}

const ReactModal = ({visible, message}) => {
  const modal = React.useMemo(() => new VanillaJSModal(), []);
  React.useEffect(() => {
    return () => modal.hideModal(); // component destroying
  }, []);
  React.useEffect(() => {
    if (visible) {
      modal.showModal(message);
    } else {
      modal.hideModal();
    }
  }, [visible]); // visible property monitoring
  React.useEffect(() => {
    modal.changeMessage(message);
  }, [message]); // message property monitoring
  return null;
};

const App = () => {
  const [modalVisible, setModalVisible] = React.useState(false);
  return (
    <div>
      <button onClick={() => setModalVisible(true)}>Show modal</button>
      <ReactModal visible={modalVisible} message="Hi there!" />
    </div>
  );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );

References

ReactJS

React - how to use pure JavaScript components
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join