Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a closing tag and a starting tag in React Component?

Is there any way to have a component of the form:

function Break(){
  return <React.Fragment></div><div className="section"></React.Fragment>;
}

Basically i'm trying to have it so that whenever component is displayed, it closes a

<div className="section>

and starts another

<div className="section">
like image 461
abcdafk Avatar asked Nov 19 '25 10:11

abcdafk


1 Answers

I imagine you are trying to render a specific no. of items (sections) from some kind of list or rows per parent element. This can be a <div className="parent"></div> for example. So that the result is:

<div>
<div className="parent">
    <div className="section></div>
    <div className="section></div>
    <div className="section></div>
</div>

<div className="parent">
    <div className="section></div>
    <div className="section></div>
    <div className="section></div>
</div>
</div>

Let's assume you have an array of numbers [1,2,3,4,5,6] you want to render inside

<div className="section></div>

e.g.

<div className="section>1</div>
<div className="section>2</div>

and so on.

You can create chunks of the array based on how many <div className="section></div> items you want to render per <div className="parent"> let's assume you want 3 <div className="section></div> per <div className="parent"> as in the code above. You can use lodash's chunk() method to do this. https://lodash.com/docs#chunk

parents = lodash.chunk([1,2,3,4,5,6], 3)
//parents is [[1,2,3], [4,5,6]]

think of each inner array as a parent element and the items inside each parent element as section elements.

therefore in react it would be rendered like:

render() {
   const parents = lodash.chunk([1,2,3,4,5,6], 3)
   return (
    <div>
     {
       parents.map((parent) => (
         <div className="parent">
         {
           parent.map((section) => (
             <div className="section">{ section }</div>
           ))
         }
         </div>
       ))
     }
    </div>
   )
}
like image 59
fritz Avatar answered Nov 21 '25 00:11

fritz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!