Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Docs: add explanation for how to import components with default props. #573

Merged
merged 9 commits into from
May 11, 2020
49 changes: 49 additions & 0 deletions docs/importing-js-into-reason.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,52 @@ module Greeting = {

let make = () => <div> <Greeting name="Peter" /> </div>;
```

### Default props and JavaScript components

Sometimes you need your JavaScript component to have a default prop. How you
handle this will depend on the details of the situation.

#### Scenario 1: The JavaScript component prop is already coded to have a default
peterpme marked this conversation as resolved.
Show resolved Hide resolved

```js
function Greeting({ name }) {
return <span>Hey {name}</span>
};

Greeting.defaultProps = {
name: "John"
};
```

Props (or any function argument) with a default is just an optional prop as far
as its signature is concerned. To bind to it, we just make the prop optional.

```reason
module Greeting = {
[@bs.module "./Greeting.js"] [@react.component]
external make: (~name: string=?) => React.element = "default";
};
```

(Note that function signatures are only concerned with types, not values. Code
like `external make: (~name="Peter") => React.element` is a syntax error.
`"Peter"` is a value, whereas `string` is a type.)

#### Scenario 2: The JavaScript component prop doesn't have a default, but we want to add one

In JavaScript, the logic for default arguments is handled at runtime inside the
function body. If our external does not already have a default, we'll need to
wrap it with our own component to add the logic.

```reason
module GreetingJs = {
[@bs.module "./Greeting.js"] [@react.component]
external make: (~name: string) => React.element = "default";
};

module Greeting = {
[@react.component]
let make = (~name="Peter") => <GreetingJs name />;
peterpme marked this conversation as resolved.
Show resolved Hide resolved
};
```