Aaron
Aaron

Reputation: 1323

React inline conditional, create multiple elements in 1 condition

Newer to React, my apologies if this is simple.

I am trying to create a notes app in Cordova with React. Everything is working fine, but I'm having trouble inserting a break after a component inline. I know that I could break this into 2 divs and use css to style them, but I am curious how I would achieve this with 1 div and breaks.

So, what I am looking for

<div id=id key=key>Subject<br/><br/>Body</div>

React doesn't seem to like adding components like this. I can make it work if I use the condition twice:

render: function(){
    var data = this.props.data;
    return data.map(function(noteData){ 
                return <div id='note' key={noteData.id}>{noteData.subj.length > 0 ? noteData.subj: ''}{noteData.subj.length > 0 ? <br/>: ''} {noteData.body}</div>;
    });
}

It doesn't allow for something like:

return <div id='note' key={noteData.id}>{noteData.subj.length > 0 ? noteData.subj<br/><br/>: ''}{noteData.body}</div>;

It doesn't seem to allow for text (unless I'm doing something wrong)

"\n" or "<br/>", with or without brackets({"<br />"}) eg.

I'm sure it has to do with how React creates elements, but... is there a single-function solution here? What is the correct way of doing this?

Upvotes: 2

Views: 3314

Answers (3)

Daniele
Daniele

Reputation: 1938

You can't return more than one element in the condition, and you are trying to return a literal with two br.

return <div id='note' key={noteData.id}>{noteData.subj.length > 0 ? noteData.subj<br/><br/>: ''}{noteData.body}</div>;

to accomplish this you have to wrap the result with a single tag, as a div for example

return <div id='note' key={noteData.id}>{noteData.subj.length > 0 ? <div>noteData.subj<br/><br/></div>: ''}{noteData.body}</div>;

Upvotes: 0

inkdeep
inkdeep

Reputation: 1127

an alternative way:

renderSubjectWithBreaks(noteData) {
  return [
    noteData.subj,
    <br/>,
    <br/>
  ]
}

and then:

return <div id='note' key={noteData.id}>
         {Boolean(noteData.subj.length) && this.renderSubjectWithBreaks(noteData)}
         {noteData.body}
       </div>;

Upvotes: 0

Joshua Underwood
Joshua Underwood

Reputation: 927

Wrap the right side of your ternary expression in an element.

noteData.subj.length > 0 ? <div>{noteData.subj}<br/><br/></div>: ''

Upvotes: 2

Related Questions