widgetti / ipyreact

React for ipywidgets that just works. No webpack, no npm, no hassle
BSD 3-Clause "New" or "Revised" License
114 stars 8 forks source link

Best practice: How to phrase traitlets into js classes? #24

Open kolibril13 opened 1 year ago

kolibril13 commented 1 year ago

I asked chatGPT to convert this code into a widget

%%react

import React, { PureComponent } from 'react';
import ReactDiffViewer from 'react-diff-viewer';

const oldCode = `Hello World`;
const newCode = `Hello New World`;

export default class App extends PureComponent {
  render = () => {
    return (
       <div
        style={{
            position: "relative",
            width: "600px",
            height: "100px",
        }}
        >
      <ReactDiffViewer oldValue={oldCode} newValue={newCode} splitView={true} />
      </div>
    );
  };
}

and after some prompting and telling the GPT how an widget is structured, it came up with this js string literal oldCode = `${this.props.my_old_code}`; syntax, which is working. My question: Is this best practice?

import ipyreact
from traitlets import Unicode, Bool

class DiffViewerWidget(ipyreact.ReactWidget):
    my_old_code = Unicode('Hello World').tag(sync=True)
    my_new_code = Unicode('Hello New World').tag(sync=True)
    split_view = Bool(True).tag(sync=True)

    _esm = """
    import React, { PureComponent } from 'react';
    import ReactDiffViewer from 'react-diff-viewer';

    export default class App extends PureComponent {
        render = () => {
            const oldCode = `${this.props.my_old_code}`;
            const newCode = `${this.props.my_new_code}`;
            return (
                <div
                    style={{
                        position: "relative",
                        width: "600px",
                        height: "100px",
                    }}
                >
                    <ReactDiffViewer oldValue={oldCode} newValue={newCode} splitView={this.props.split_view} />
                </div>
            );
        };
    }
    """

d = DiffViewerWidget(my_old_code='Hello World', my_new_code='Hello New World')
d

with the GPT explaination:

In this code, my_old_code and my_new_code are traits defined in the Jupyter widget DiffViewerWidget. When the widget is rendered, their values will be available as properties of the props object in the React component. The template literals use ${} to embed the values of my_old_code and my_new_code inside a string.

maartenbreddels commented 1 year ago

Depends on your taste. Modern react uses functions instead of classes. Both are fine. I prefer functions. So yes, this is correct :)