Minh Thai
Minh Thai

Reputation: 578

Reason React using js component

I'm having trouble with js interop. I'm trying to use a js component react-slick like this:

// src/interop/Carousel.js
import React from 'react'
import Slider from 'react-slick'

export function Carousel(props) {
  return (
    <Slider>
      <div>
        <h3>{props.name} 1</h3>
      </div>
    </Slider>
  )
}


/* src/Carousel.re */
[@bs.module  "./interop/Carousel"] [@react.component]
external  make: (~name: string) =>  React.element  =  "";

/* src/index.re */
ReactDOMRe.renderToElementWithId(<Carousel  name="ahaha"  />,  "carousel");

But met with this error in webpack:

ERROR in ./lib/js/src/Index.bs.js
Module not found: Error: Can't resolve './interop/Carousel' in '[...]/reason_react_example/lib/js/src'
 @ ./lib/js/src/Index.bs.js 6:15-44

So it looks like BS doesn't consider Carousel.js file when compile?

btw, I'm following this reason-react doc

Upvotes: 1

Views: 489

Answers (2)

Minh Thai
Minh Thai

Reputation: 578

After some tweaks, here is what works for me:

// lib/js/src/interop/Carousel.js
import React from 'react'
import Slider from 'react-slick'

const Carousel = props => {
  return (
    <Slider>
      <div>
        <h3>{props.name} 1</h3>
      </div>
    </Slider>
  )
}

export default Carousel


// src/Carousel.re    
[@bs.module "./interop/Carousel"] [@react.component]
external make: (~name: string) => React.element = "default"; // handle default export

// src/Index.re
ReactDOMRe.renderToElementWithId(<Carousel name="it works!" />, "carousel");

Since Carousel.js is using es6 and jsx, I need to setup webpack to work with it (es6, jsx). And bsconfig.json needs to have these settings:

"reason": {
  "react-jsx": 3
},
"package-specs": [
  {
    "module": "commonjs",
    "in-source": false
  }
]

Upvotes: 1

glennsl
glennsl

Reputation: 29106

BuckleScript will put the generated js artifacts in lib/js/... by default, so you either have to write your imports relative to that, or configure bsb to put the artifacts alongside the source files. You do the latter by setting "in-source": true for a given package-spec in bsconfig.json. E.g.:

{
  "package-specs": {
    "module": "commonjs",
    "in-source": true
  }
}

See the documentation on the package-specs configuration item.

Upvotes: 2

Related Questions