Import / Export ReactJS
Reusing existing React components in ReScript is straightforward. This guide will walk you through the steps required to import and use React components within ReScript, including defining component props and handling various import scenarios.
Basic Example
To reuse a React component in ReScript, create a new module, specify the component's location, and define its props.
Importing from Relative Paths
You can import components from relative file paths using the @module
attribute.
Use "default" to indicate the default export, or specify a named export if needed.
Named Export Example
// Equivalent of import { Foo } from "bar"
module Foo = {
@module("bar") @react.component
external make: unit => React.element = "Foo"
}
Defining Props Types
You can define a separate type for your component's props within the module.
Props Type Example
Optional Props
To define optional props, use the ?
symbol.
module Confetti = {
type confettiProps = {
width: int,
height: int,
initialVelocityX?: int,
initialVelocityY?: int,
}
@module("react-confetti") @react.component(: confettiProps)
external make: confettiProps => React.element = "default"
}
@react.component
let make = () => {
<Confetti width={300} height={300} />
}
Extending Built-in DOM Nodes
To accept existing DOM props for a component, extend the JsxDOM.domProps
type.
In this example width
and height
can be set because JsxDOM.domProps
was spread into fooProps
.