cmiotk
cmiotk

Reputation: 315

React JS | Render Multiple Elements

I am trying to create a email in React using the MJML email library. It runs off react and I have it all working but I need to render 2 sections rather than 1. When I render 1 it doesn't appear properly on the webpage as I need them to be different sizes.

When I try and wrap the elements within a array the return become null, take out one of the sections and it gets returned.

Any help would be appreciated, here is the code.

render() {
    const { mjAttribute } = this.props
    const content = [this.renderEmailOverhead()]
    const innerContent = [this.renderEmailBanner(), this.renderEmailTitle(), this.renderEmailText(), this.renderEmailDivider]

    return ([
        <Section full-width='full-width' padding-top="0">
            { content }
        </Section>,
        <Section>
            { innerContent }
        </Section>
    ])
}

Upvotes: 0

Views: 2432

Answers (2)

iRyusa
iRyusa

Reputation: 394

Well, render method of a component can only return one element. so you'll have to wrap it in a divas Zargold mentioned.

Note that MJML component are more than a standard React component.

It has some internal logic not available in a React context. IMO you should generate MJML as standard HTML element and render it with a renderToStaticMarkup then pass it to mjml2html function as a string and mjml will compiles

 return (
   <mjml>
     <mj-body>
       <mj-container>
         ... // your sections goes here
       </mj-container>
     </mj-body>
   </mjml>
 )

Note that I don't think React is the best suited for this kind of work, I would recommend you to use a templating language such as mustache/handlebars which fit better.

Upvotes: 1

Zargold
Zargold

Reputation: 2092

You cannot use JSX interspersed with JavaScript like that... you could either do (you must have only one parent/root element).

<div>
<Section full-width='full-width' padding-top="0">
    { content }
</Section>
<Section>
    { innerContent }
</Section>
</div>

Or You could if you insist on using an array for some reason:

renderSection(content, fullWidth){
return (
  <Section
    full-width={fullWidth ? 'full-width' : false}
    style={{paddingTop: fullWidth ? 0 : 'auto'}}
  >
  {content}
  </Section>
)
}
render(){
 let contents = [content, innerContent]
return(
    <div>
    {contents.map(section, i => renderSection(section, i % 2 === 0))
    </div>
)

Upvotes: 0

Related Questions