Getting the named type of props for a React component

Suppose I’ve written a React component and elsewhere I want to construct a props object that I can feed into that component. How to do this? Ideally I’d like to be able to do something like Component.make to make the component, and Component.propType to see the prop type. I thought something like this existed before, Component.makeProps, but can’t do this now.

@react.component
let make = (~x, ~y) => {
  <div>
    <div> {React.string("x: " ++ Int.toString(x))} </div>
    <div> {React.string("y: " ++ Int.toString(y))} </div>
  </div>
}

let makeParamsDoubled : nameOfPropsTypeHere = (x, y) => {
  x: x * 2,
  y: y * 2,
}

When you call @react.component, under the hood, it also declares a props type, which could be used elsewhere:

@react.component()
let make = (~x, ~y) => {
  <div>
    <div> {React.string("x: " ++ Int.toString(x))} </div>
    <div> {React.string("y: " ++ Int.toString(y))} </div>
  </div>
}

let makeParamsDoubled = ({x, y}: props<int, int>) => {
  x: x * 2,
  y: y * 2,
}

However, as you might have noticed, this type takes in a generic for each prop the component has, which can be cumbersome. As such, it might be easier to declare the type separately, and pass it to the component; the generated props will not need generics.

type myProps = {
  x: int,
  y: int
}

@react.component(:myProps)
let make = (~x, ~y) => {
  <div>
    <div> {React.string("x: " ++ Int.toString(x))} </div>
    <div> {React.string("y: " ++ Int.toString(y))} </div>
  </div>
}

let makeParamsDoubled = ({x, y}: props) => {
  x: x * 2,
  y: y * 2,
}
2 Likes