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
    An Interview with Eric Meyer

    Your early CSS books were instrumental in pushing my love for front end technologies. What was it about CSS that you fell in love with and drove you to write about it? At first blush, it was the simplicity of it as compared to the table-and-spacer...

  • By
    Write Better JavaScript with Promises

    You've probably heard the talk around the water cooler about how promises are the future. All of the cool kids are using them, but you don't see what makes them so special. Can't you just use a callback? What's the big deal? In this article, we'll...

Incredible Demos

Discussion

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