Basic question regarding plugins + passing Python dicts to React

Hello,

I’m trying to adapt an existing React component into a Dash plugin.

I’m very new to React/js/JSX, but I have something working. However, some of React component Props are objects – and when I try to pass a Python dict on the Dash side, it simply doesn’t work.

The only way I’ve managed to get it to work is to use json.dumps(my_python_dict) on the Dash side to encode it as a string, and then create a dummy Prop on the React side that takes the string, decodes it, and passes it along to the actual Prop as a JavaScript object. This feels like I’m doing something wrong, is there a better way to do this?

Many thanks,

Matt

This should work. The serialization from Python to JSON is done automatically (see dash/dash/dash.py at 3cd6a78ee21620c77ccdbdf2724c995872383666 · plotly/dash · GitHub).

What do you mean by “it simply doesn’t work” - is it failing or does it convert it incorrectly or does it fail to convert it back from a JSON string to a JS structure? Could you post a small, reproducable example?

I’d also recommend checking out some of the existing component’s, for example the “Checklist” is relatively simple: dash-core-components/src/components/Checklist.react.js at 25e8e83f0195152a9e769b128ccc21674179a2e6 · plotly/dash-core-components · GitHub

Thanks very much for the reply Chris – on trying to recreate a minimal example, I have found that this does work! :slight_smile:

Thinking about it more, I think I know what I did wrong … The error was ‘Objects are not valid as a React child’, I suspect what was going wrong was that I inadvertently trying to render the object (dict) in the DOM, and React didn’t know how to do that (i.e. in Python, print(my_dict) is perfectly valid, but in JS(X) writing <div> {myDict} </div> will not print a string version of that dict).

Hopefully if someone else stumbles across this thread they won’t make the same mistake I did !

2 Likes