4

React.isValidElement

 3 years ago
source link: https://davidwalsh.name/react-isvalidelement
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

React.isValidElement

By David Walsh on December 14, 2020  

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 :
    <div class="text-message">{content}</div>
}

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!

Discussion

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

 Continue this conversation via emailGet only replies to your comment, the best of the rest, as well as a daily recap of all comments on this post. No more than a few emails daily, which you can reply to/unsubscribe from directly from your inbox.

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK