Quantcast
Channel: ReScript Forum - Latest posts
Viewing all articles
Browse latest Browse all 2592

Static component properties in React

$
0
0

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 */

Viewing all articles
Browse latest Browse all 2592

Trending Articles