Home > other >  Returning nested divs in react
Returning nested divs in react

Time:07-06

I am trying to return a structure similar to this

<div style="someCSS">
  <div style="someOtherCSS"></div>
  <div style="someOtherCSS"></div>
</div>
<div style="someCSS">
  <div style="someOtherCSS"></div>
  <div style="someOtherCSS"></div>
  <div style="someOtherCSS"></div>
</div>

I am working around this idea, but it's not quite right, and I don't know what to do.

const nestedDivs = () => {
    for (let i = 0; i <= x; i  ) {
      for (let j = 0; j <= y; j  ) {
         let someOtherCSS{
          borderColor: '#fff',
          borderSize: '1px',
          borderStyle: 'solid',
          background: '#ffcc00',
         };
      fooStyle.push(<div style={someOtherCSS}></div>);
      }
       let someCSS{
          borderColor: '#fff',
          borderSize: '1px',
          borderStyle: 'solid',
          background: '#ff0000',
         };
      fooStyle.unshift(<div style={someCSS}></div>);
    }
    return fooStyle;
}

CodePudding user response:

If your code is executing properly and just have issue with appending someOtherCSS divs into someCSS, then you can try this,

const nestedDivs = () => {
    for (let i = 0; i <= x; i  ) {
        const innerDives = [];
        for (let j = 0; j <= y; j  ) {
            let someOtherCSS{
                borderColor: '#fff',
                borderSize: '1px',
                borderStyle: 'solid',
                background: '#ffcc00',
            }
            innerDives.push(<div style={someOtherCSS}></div>);
        }
        let someCSS{
            borderColor: '#fff',
            borderSize: '1px',
            borderStyle: 'solid',
            background: '#ff0000',
        }
        fooStyle.push(<div style={someCSS}>{innerDives}</div>);
    }
    return fooStyle;
}

Hope this will helpful to you! Happy coding...

CodePudding user response:

You can give a below try also, it uses text for concat the html and then dangerouslySetInnerHTML to string HTML.

import React from 'react';
import './App.css';

function App() {
  let someHtml = ``;
  let x = 5;
  let y = 10;
  for (let i = 0; i <= x; i  ) {
    someHtml  = `<div className='someCSS'>`
    for (let j = 0; j <= y; j  ) {
      someHtml  = `<div className='someOtherCSS'></div>`;
    }
    someHtml  = '</div>'
  }


  return (
    <div className="App" dangerouslySetInnerHTML={{__html: someHtml}} />
  );
}

export default App;
  • Related