bigblind bigblind - 1 year ago 60
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;
inputElement = <div className="col-sm-10">
} else {
inputElement = <span className="col-sm-10">

Based on whether
, I'm wrapping
in a span or a div. Is there a clean way to do this without repeating
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 Source

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>

  <App horizontal={true} />,
<script src=""></script>
<script src=""></script>

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download