1

I'm using the react-jsx-parser npm package and I have this code:

Builder.tsx

import JsxParser from "react-jsx-parser";

export default function Builder() {
  const a = `
              <>
                {data.map((el, i) => (
                  <div key={i}>{el}</div>
                ))}
              </>
             `;
  return <JsxParser bindings={{ data: [1, 2] }} jsx={a} />;
}

But this doesn't work and I'm getting the error down below, I've done some research and can't find any solution.

Error

Esc Official
  • 99
  • 10

2 Answers2

1

Specify your data, becuase now data is undefined and map works only over arrays!

SMEET KOTHARI
  • 59
  • 1
  • 7
1

Your data can be passed successfully. If you change the a const to the following, it will show a and b correctly:

const a = `
    { data }
`;

In html:

...
<div>
"a"
"b"
</div>
...

I think the library is not smart enough to parse the function literally as it may require extra work to interpret and evaluate the code. If you hardcode the array like below, it will still throw the same error:

const a = `
    { ["a", "b"].map((d) => d)}
`;

So to get want you want, you may need to process and decorate the data in the binding section. It may or may not be what you want:

bindings={{
  data: ["a", "b"].map((el, i) => (
    <div key={i}>
      {el}
    </div>
  ))
}}

Here is the codesandbox for demo

Mic Fung
  • 5,404
  • 2
  • 7
  • 17