Interface for react component

Hello everybody!

I’m not sure how properly write an interface for a react component. Lets say I have this component:

// Titlebar.res
@react.component
    let make = (
      ~title: string,
      ~minimize: bool=true,
      ~maximize: bool=true,
      ~close: bool=true,
    ) => {
      <div className="titlebar">
        <div className="titlebar__title"> {React.string(title)} </div>
        <div className="titlebar__actions">
          {minimize
            ? <div className="titlebar__action titlebar__minimize"> {React.string("-")} </div>
            : <> </>}
          {maximize
            ? <div className="titlebar__action titlebar__maximize"> {React.string("+")} </div>
            : <> </>}
          {close
            ? <div className="titlebar__action titlebar__close"> {React.string("x")} </div>
            : <> </>}
        </div>
      </div>
    }

How corresponding resi file should look like?

Interface below gives me an error: The value makeProps can’t be found in Titlebar

// Titlebar.resi
let make: React.component<{
  "close": option<bool>,
  "maximize": option<bool>,
  "minimize": option<bool>,
  "title": string,
}>

Writing interface files for React components is actually easier than it looks, but it should probably be better documented.

Here is what you want:

  @react.component
  let make: (
    ~title: string,
    ~minimize: bool=?,
    ~maximize: bool=?,
    ~close: bool=?,
  ) => React.element
2 Likes

That worked, thank you! I agree, this should be documented. React’s hot reload won’t work if there’s more than one export, so it’s really important to have that interface

2 Likes

Is there a way to write a type for this part?

(
    ~title: string,
    ~minimize: bool=?,
    ~maximize: bool=?,
    ~close: bool=?,
  )

What do you mean? Isn’t this a type already?

I mean something like code below

type props = {
  title: string,
  minimize: option<bool>,
  maximize: option<bool>,
  close: option<bool>
}

I’m just trying to understand (~prop1: type, ~prop2: type) syntax. Is this a destructured record/object? It looks like python’s **kwargs

This should help!

How would you use this type?

This syntax is similar to kwargs in python or destructured args in js, so my first thought was I could write a type out of that. But now I see, that it’s just a different syntax for args and it’s not represented by some dict (like in python) or object (like in js).

Nope, it’s just the syntax for functions with labeled arguments, but if you really want to, you can also define the type of the function beforehand and reuse it for different components.

Don’t forget to mark the discussion as solved if you think it indeed is.

Thank you for your help. Such a nice community