简体   繁体   中英

Render React Component Depending on its Type

I was wondering if there was a way, in React, to conditionally render components based on their type. According to the documentation, you can define the a component's prop types in the following way:

MyComponent.propTypes = {
  description: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),
};

Is there a way, using the framework to check for the type and render a component differently depending on whether the received prop data is a string or array ?

I know I can use raw JS to determine this, by using type of or checking for properties of an array on the data.

if (typeof description === "string") { /* render string component */ }
else { /* render array component */ }

I was wondering if React, had a built-in, more robust method of doing this.

I was wondering if React, had a built-in, more robust method of doing this.

description is a union prop type.

Thus, you need to have a rendering logic by making use of render props .

const StringDescription = (props) => {...}
const ArrayDescription = (props) => {...}

function renderDescription(description) { // rendering logic / strategy
  switch(typeof description) {
    case 'string':
      return <StringDescription />;
    default:
      return <ArrayDescription />;
  }
}

<Description
  description={description}
  render={renderDescription} // render prop
/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM