React.isValidElement

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 […]

The post React.isValidElement appeared first on David Walsh Blog.


This content originally appeared on David Walsh Blog and was authored by David Walsh

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!

The post React.isValidElement appeared first on David Walsh Blog.


This content originally appeared on David Walsh Blog and was authored by David Walsh


Print Share Comment Cite Upload Translate Updates
APA

David Walsh | Sciencx (2020-12-14T10:35:26+00:00) React.isValidElement. Retrieved from https://www.scien.cx/2020/12/14/react-isvalidelement/

MLA
" » React.isValidElement." David Walsh | Sciencx - Monday December 14, 2020, https://www.scien.cx/2020/12/14/react-isvalidelement/
HARVARD
David Walsh | Sciencx Monday December 14, 2020 » React.isValidElement., viewed ,<https://www.scien.cx/2020/12/14/react-isvalidelement/>
VANCOUVER
David Walsh | Sciencx - » React.isValidElement. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2020/12/14/react-isvalidelement/
CHICAGO
" » React.isValidElement." David Walsh | Sciencx - Accessed . https://www.scien.cx/2020/12/14/react-isvalidelement/
IEEE
" » React.isValidElement." David Walsh | Sciencx [Online]. Available: https://www.scien.cx/2020/12/14/react-isvalidelement/. [Accessed: ]
rf:citation
» React.isValidElement | David Walsh | Sciencx | https://www.scien.cx/2020/12/14/react-isvalidelement/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.