DEV Community

Discussion on: The 10 Component Commandments

Collapse
 
pedromass profile image
Pedro Mass

For Tip 2. Allow for contextual semantics

function Grid({ as: Element, ...props }) {
  return <Element className="grid" {...props} />
}
Grid.defaultProps = {
  as: 'div',
};

What would the propType be?

Something like this?

Grid.propTypes = {
  as: PropTypes.oneOfType([PropTypes.string, PropTypes.elementType])
};
Collapse
 
selbekk profile image
selbekk

Yeah that would be it!

Collapse
 
asherccohen profile image
Asher Cohen

This was the one I preferred. But in a non-typescript world that would require a lot of conditions to return the right element type.

Am I right?

Collapse
 
selbekk profile image
selbekk

Good question! It’s not a very easy type to get right, especially if you want the correct props of the as element to be applied as well. It is doable though, with a drizzle of keyof and some other ts ninja tricks. I’m not a great TS dev yet, and I’m on my phone atm.

There is lots of prior art here - look at reach UI or styled components’types for possible impoementations