Static component properties in React

Hello,

I want to use CLI - React Email and Iโ€™m wondering how I would write a binding for

export default function Email(props) {
  return (
    <div>
      <a src={props.source}>click here if you want candy ๐Ÿ‘€</a>
    </div>
  )
}

Email.PreviewProps = {
  source: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ'
}

I canโ€™t quite figure out the Email.PreviewProps part.

I guess the closest you can do is writing a binding with a @get attribute to the make function. Iโ€™ll write it down as soon as Iโ€™m back on my computer.

1 Like

Hereโ€™s an approach using %raw:

module Email = {
  @react.component
  let make = (~source) => {
    <div>
      <a src={source}> {React.string("click here if you want candy ๐Ÿ‘€")} </a>
    </div>
  }
}

let setPreviewProps: ('a => React.element, 'a) => unit = %raw(`
  function setPreviewProps(component, props) {
  	component.PreviewProps = props
  }
  `)

Email.make->setPreviewProps({
  source: "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
})

Playground link:

And, you could of course do the same with an actual binding to skip the intermediate function, just like @tsnobip says:

module Email = {
  @react.component
  let make = (~source) => {
    <div>
      <a src={source}> {React.string("click here if you want candy ๐Ÿ‘€")} </a>
    </div>
  }
}

@set
external setPreviewProps: ('a => React.element, 'a) => unit = "PreviewProps"

Email.make->setPreviewProps({
  source: "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
})

Outputs this JS:

// Generated by ReScript, PLEASE EDIT WITH CARE

import * as JsxRuntime from "react/jsx-runtime";

function Playground$Email(props) {
  return JsxRuntime.jsx("div", {
              children: JsxRuntime.jsx("a", {
                    children: "click here if you want candy ๐Ÿ‘€",
                    src: props.source
                  })
            });
}

var Email = {
  make: Playground$Email
};

Playground$Email.PreviewProps = {
  source: "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
};

export {
  Email ,
}
/*  Not a pure module */
3 Likes

Yep my bad I meant @set attribute ^^

3 Likes