DEV Community

Rickard Natt och Dag
Rickard Natt och Dag

Posted on • Originally published at willcodefor.beer on

ReScript: Using React components

In the previous post, we learned how to create React components in ReScript. In this post, we'll learn how to import and use them in other components. We'll start by making some adjustments to the <Button> we created.

// Button.res
@react.component
let make = (~children, ~onClick) => {
  <button onClick> children </button>
}
Enter fullscreen mode Exit fullscreen mode

We have changed the button child from React.string("Click me") to childrenand added a prop for ~children in the component function. This way we can reuse the button with different contents. The type of the children prop is inferred asReact.element and it is required.

// App.res
@react.component
let make = () => {
  <div> <Button /> </div>
}
Enter fullscreen mode Exit fullscreen mode

Here we use our <Button> component inside another component called <App>. As we saw in the last post, all files are modules and globally available in ReScript. Therefore we can add the <Button> to our JSX without having to import any files beforehand.

If we save now, we get an error in the compiler that we are missing the required properties for the <Button>.

  1  @react.component
  2  let make = () => {
  3    <div> <Button /> </div>
  4  }

  This has type:
    (~children: 'a, ~onClick: 'b) => {"children": 'a, "onClick": 'b}
  Somewhere wanted:
    {"children": React.element, "onClick": ReactEvent.Mouse.t => unit}
Enter fullscreen mode Exit fullscreen mode

Let's add the props to satisfy the compiler.

@react.component
let make = () => {
  <div>
    <Button onClick={_event => ()}> {React.string("Click me")} </Button>
  </div>
}
Enter fullscreen mode Exit fullscreen mode

onClick gets a function defined as _event => (). The underscore beforeevent tells the compiler that the variable is unused and we return a unit, (), which compiles to JavaScript's undefined.

Lastly, we re-add the button text from before as a child to <Button>, and we have successfully used our <Button> component!

Top comments (0)