Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I append external DOM to React component?

I have a page with a form rendered in the server, it handles validation, and the correct value for the selects.

I want to hide the DOM of that form, and append it into a react component so I can use it in react-router.

const NewItem = React.createClass({  
  render() {                          
    return (                          
      <div>                           
        <h1>New item</h1>
        {/* I WANT THE FORM FROM THE PAGE HERE*/}
      </div>                          
    )                                 
  }                                   
})                                    

What is the best way to do it?

like image 775
Adrian Ribao Avatar asked Sep 29 '15 16:09

Adrian Ribao


People also ask

How do I import an external js file into ReactJS component?

Installation: Open a terminal inside your ReactJS project folder and write the following code to install react-script-tag Package. Import 'ScriptTag' component: Import the built-in 'ScriptTag' component from the react-script-tag library at the top of the file where we want to add the script tag.

Which method is used to add components or elements to the DOM in React?

AppendChild. The simplest, most well-known method of appending an element to the DOM is certainly the appendChild() .

Can you use the DOM in React?

React implements a browser-independent DOM system for performance and cross-browser compatibility. We took the opportunity to clean up a few rough edges in browser DOM implementations. In React, all DOM properties and attributes (including event handlers) should be camelCased.

How do you append in React?

push() - append content in array. unshift() - prepend content in array. Append element in react by using below function : Appending content in array by using push function and with the help of state we are render the content in browser.


3 Answers

You have full access to the DOM in componentDidMount. You can use refs to access the specific DOM element you want.

var NewItem = React.createClass({
    componentDidMount: function () {
        this.refs.formTarget.appendChild(myFormDomElement);
    },

    render: function () {
        return React.DOM.div(null,
            React.DOM.h1(null, "New item"),
            React.DOM.div({ref: "formTarget"}));
    }
});

Note that in 0.14, a ref is a raw DOM element. Prior to that a ref was a react component and you had to call React.findDOMNode(it) to get the actual DOM element.

like image 156
August Lilleaas Avatar answered Oct 16 '22 16:10

August Lilleaas


React > 16.3

Try using portals like in this component:

import {Component} from 'react';
import {createPortal} from 'react-dom';
import PropTypes from 'prop-types';

class DOMPortal extends Component {
    constructor(props) {
        super(props);
        this.el = document.createElement(props.component);
    }

    componentDidMount() {
        this.props.parentEl.appendChild(this.el);
    }

    componentWillUnmount() {
        this.props.parentEl.removeChild(this.el);
    }

    render() {
        return createPortal(
            this.props.children,
            this.el,
        );
    }
}

DOMPortal.propTypes = {
    parentEl: PropTypes.object.isRequired,
    component: PropTypes.string,
};

DOMPortal.defaultProps = {
    component: 'div',
};

Now you can pass your external DOM reference as the parentEl props to it:

<DOMPortal parentEl={decorator.contentWidget.domNode}>...children</DOMPortal>

React < 16.3

Using this.refs is "deprecated", try this instead :

render() {
 return <div ref={(DOMNodeRef) => {
                 this.componentRef=DOMNodeRef;
                }}>
      ...
      </div>;
 }

Then this.componentRef will be accesible in componentDidMount() so you can append your external DOM element:

componentDidMount(){
  this.componentRef.appendChild(externalDOMelement);
}

Notes:

Remember that this.componentRef changes over time (renders()), so you must update it wherever you are passing it to.

Check for a defined reference before using it: if(this.componentRef){// ... your code}

Functional Components' refs are handled differently.

Source:

React Doc

like image 25
David I. Samudio Avatar answered Oct 16 '22 16:10

David I. Samudio


React gives us the functionality dangerouslySetInnerHTML. it gives us the support of adding HTML element. for example

function createMarkup() {
  return {__html: 'First &middot; Second'};
}

function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />;
}

You can also use portals introduced in react-16 for appending React component anywhere in the tree by using following code.

ReactDOM.createPortal(child, container)

follow following link Portals for refference

like image 1
Japesh Avatar answered Oct 16 '22 17:10

Japesh