gabrielAnzaldo
gabrielAnzaldo

Reputation: 3304

How to create a react component from a DOM node?

I would like to create a react component from a DOM node (pretty small one, nothing crazy), for example:

//this footer is plain html and css, not a react component
const Footer = document.getElementById("#anAwesomeFooter")

and in some way use it anywhere in my app:

// before doing some magic
<Main>
 <Footer />
<Main />

Upvotes: 3

Views: 5650

Answers (2)

Leonardo Maddio
Leonardo Maddio

Reputation: 162

import React from 'react';

const Footer = () => (<div>Footer of some div outside the Main component hierarchy</div>);

const SomeComponent = () => {
  const elementToAttach = document.getElementById('someElementId');
  return (
    <Main>
      {React.createPortal(Footer, this.elementToAttach)}
    </Main>
  );
};

You can do the getElementById in the constructor to run only once, but thats depends if you know the element is already rendered

Upvotes: 0

n9iels
n9iels

Reputation: 895

I think the closets you can get, is getting the content of the DOM node in the componentDidMount, and append it to a rendered element. This question and answers is related. https://stackoverflow.com/a/53897595/4703833

Upvotes: 0

Related Questions