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
    Page Visibility API

    One event that's always been lacking within the document is a signal for when the user is looking at a given tab, or another tab. When does the user switch off our site to look at something else? When do they come back?

  • By
    Chris Coyier’s Favorite CodePen Demos

    David asked me if I'd be up for a guest post picking out some of my favorite Pens from CodePen. A daunting task! There are so many! I managed to pick a few though that have blown me away over the past few months. If you...

Incredible Demos

Discussion

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