0

Is it possible to have a React component what can find out dynamically what props its got?

Example:

type BaseType = {
   baseProp?: ...
   as?: ...
}

type Extended = {
   extendedProp?: ...
}

<Base /> // expected props => { baseProp }
<Base as={ExtendedComponent} extendedProp={...} /> // expected props => { baseProp, extendedProp } 

1 Answer 1

1

Taking a cue from this answer we can, using intersections first infer the type of the props from as and then use those props to validate any extra properties:

type BaseType = {
  baseProp?: number
}

type Extended = {
  extendedProp?: string
}

declare const ExtendedComponent: React.FC<Extended>
function Base<T = {}>(p: BaseType & { as? : React.ComponentType<T>} & T): React.ReactElement{
  if(p.as) {
    const Child = p.as;
    return <div>{p.baseProp}<Child {...p as T}></Child></div>
  }else {
    return <div>{p.baseProp}</div>
  }
}


let s = <Base /> // expected props => { baseProp }
let a = <Base as={ExtendedComponent} extendedProp="a" /> 
Sign up to request clarification or add additional context in comments.

1 Comment

Wow... been trying to achieve this for hours... :D. Thought there is a solution as this can be handled in compile time. Thanks alot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.