React.isValidElement

By  on  

Knowing what input type you've received is hugely important in JavaScript, which is a big reason for Flow and TypeScript's rise. One such case where it's useful to know what an object represents is if the input is a string or a React element.

To detect if an object is a React element, you can use React.isValidElement(obj):

// Add a wrapping DIV if the content isn't a React element

// PropTypes.oneOfType([PropTypes.string, PropTypes.element])
render() {
  const { content } = this.props

  React.isValidElement(content)) ?
    content :
    
{content}
}

I really like that React.isValidElement allows us to create flexible elements that accept React elements or strings; hugely useful in generic components like modals, alerts, and everywhere else!

Recent Features

  • By
    fetch API

    One of the worst kept secrets about AJAX on the web is that the underlying API for it, XMLHttpRequest, wasn't really made for what we've been using it for.  We've done well to create elegant APIs around XHR but we know we can do better.  Our effort to...

  • By
    Send Text Messages with PHP

    Kids these days, I tell ya.  All they care about is the technology.  The video games.  The bottled water.  Oh, and the texting, always the texting.  Back in my day, all we had was...OK, I had all of these things too.  But I still don't get...

Incredible Demos

  • By
    MooTools TextOverlap Plugin

    Developers everywhere seem to be looking for different ways to make use of JavaScript libraries. Some creations are extremely practical, others aren't. This one may be more on the "aren't" side but used correctly, my TextOverlap plugin could add another interesting design element...

  • By
    Vibration API

    Many of the new APIs provided to us by browser vendors are more targeted toward the mobile user than the desktop user.  One of those simple APIs the Vibration API.  The Vibration API allows developers to direct the device, using JavaScript, to vibrate in...

Discussion

    Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!