bigblind bigblind - 20 days ago 6
Javascript Question

Change the element wrapping its children based on a condition in JSX

I wasn't sure how to title this question, but I'm basically wondering if there's a cleaner way to do this:

var inputElement;
if(props.horizontal){
inputElement = <div className="col-sm-10">
{props.children}
{help}
</div>
} else {
inputElement = <span className="col-sm-10">
{props.children}
{help}
</span>
}


Based on whether
props.vertical
is
true
, I'm wrapping
{props.children}
and
{help}
in a span or a div. Is there a clean way to do this without repeating
{props.children}{help}
twice? Is there a way to put the type of element I want in a variable, and then use that in jsx to wrap these?

Answer

React Elements can be constructed either from a Component, or a string representing an HTML tag.

That means, an approach like the the following works perfectly fine:

const App = (props) => {
  const wrapper = props.horizontal ? 'div' : 'span'
  return <wrapper className="col-sm-10">Content</wrapper>
}

ReactDOM.render(
  <App horizontal={true} />,
  document.getElementById('app')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'></div>