React - How to create div and put into it a existing child

Viewed 53

I would like to create div and put into it a existing child.

Let's say I am using some UI component which gives me some structure, it looks more or less like this. Now I would like to wrap part of this structure in my own div. In this case I want to wrap content into my own div.

<div class="heading"></div>
<div class="content"></div>
<div class="footer"></div>

So my Idea was:

useEffect(() => {
  const wrapper = document.querySelector('.content');
  wrapper &&  React.createElement('div', wrapper);
}, [dep])

But this does not create any div because I still see content without parent above

3 Answers

Just create a wrapper component and reuse it within your app.

export const Layout = ({ children, header, footer }) =>
  <div className="layout">
      <div className="header">{header}</div>
      <div className="content">{children}</div>
      <div className="footer">{footer}</div>
  </div>
  
  
Layout.defaultProps = {
    children: <></>,
    header: <></>,
    footer: <></>
}  

enter image description here

  <div>
  <div className="heading">1</div>
  <div className="content">2</div>
  <div className="footer"> 3</div>
</div>

useEffect(() => {
const content = document.querySelector('.content');
const newContent = document.querySelector('.wrapper .content');
let chilItem = document.createElement('div');
let newItem = document.createElement('div');
newItem.className = 'wrapper';
chilItem.className = 'content';
newItem.appendChild(chilItem);
!newContent && content.parentNode.replaceChild(newItem, content);
  }, []);

The approach in React is different.

You create a Layout component

Layout.jsx

export default function Layout(props) {

return <div>
         <div class="heading">{props.heading}</div>
         <div class="content">{props.children}</div>
         <div class="footer">{props.heading}</div>
       </div>

}

In your sub component

ComponentA.jsx

export default function ComponentA() {

    return <Layout heading={<h1>Company Name</h1>} footer={<div>footer contents</div>}>        
   All you contents, this will be displayed in div
   with class content. All contents here will be 
   available in props.childer of Layout component.
</Layout>
}

More details here - https://reactjs.org/docs/composition-vs-inheritance.html

Related