EN
React - how to use pure JavaScript components
0
points
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
ormessage
property - to monitor these poperty values.
- with an empty array of dependencies (
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 );