Convert JS Object to Reason Record in ReasonReact

reasonreact

#1

I have an object I am passing to a React component which is a ReasonReact component wrapped for JS.

import React from "react";
import ReactDOM from "react-dom";

import App from "../lib/es6_global/src/App";

const data = {
  name: "Adam Long",
  age: 31,
  profession: "developer"
};

ReactDOM.render(<App data={data} />, document.querySelector("#root"));

Inside of my ReasonReact component I would like to convert the JS object to a Reason record. I have only been able to convert it to a BuckleScript object.

let component = ReasonReact.statelessComponent("App");

[@bs.deriving abstract]
type data = {
  name: string,
  age: int,
  profession: string,
};

let make = (~data, _children) => {
  ...component,
  render: _self => {
    let name = data->nameGet;
    let age = data->ageGet |> string_of_int;
    let profession = data->professionGet;

    <div>
      {
        {j|Hello 👋. My name is $name. I am $age years old. I am a $profession.|j}
        |> ReasonReact.string
      }
    </div>;
  },
};

type jsProps = {data};

let default =
  ReasonReact.wrapReasonForJs(~component, jsProps =>
    make(~data=jsProps##data, [||])
  );

Ideally I would like to desctruture the record to pluck off the values:

let { name, age, profession } = data;

Is there a way for me to convert the JS object into a Reason record or is this not possible?


#2

If you want to convert from and between js objects and reason records, you can use [@bs.deriving jsConverter] instead of [@bs.deriving abstract].

Documentation can be found here:

Example:


#3

Please note that you can not convert nested objects, just shallow ones