If you want to integrate your javascript or non-reactjs application with a reactjs app and be able to access
reactjs components and call their methods to execute actions or get information out of them, in this quick
tips episode, you will learn how. Above is the vid and below you will find some useful notes.
- 1.
Pre-reqs
-
Have node.js installed
-
- 2.
Exposing React JS to Javascript or non-reactjs applications
-
For a component created using classes you just need to add a ref attribute when including the component:
<ComponentName ref={(componentReference) => {window.componentReference = componentReference}}/>
-
If it is a component created using functions then, you would also need: to import forwardRef and useImperativeHandle
import React, { useState, forwardRef, useImperativeHandle } from 'react';
-
Use forwardRef when defining the functional component:
const YourFunctionalComponent = forwardRef((props, ref) => {
-
Finally, inside the useImperativeHandle hook, you need to define the methods you need to expose:
useImperativeHandle(ref, () => ({ methodToExpose(name) { //Some code here! } }));
-
- 3.
Comentarios
Publicar un comentario