r/reactjs • • Jul 28 '19

Show /r/reactjs ScriptUI: Write React without JSX

https://github.com/anater/ScriptUI
3 Upvotes

26 comments sorted by

4

u/[deleted] Jul 28 '19

I'm really not following how this would work for a complex example.

Can you translate this ContactUs form into ScriptUI so I can see how props are supposed to be passed down?

function ContactUs(props) {

  const handleChange = (e) => { /* setState({ [e.target.name]: [e.target.value] }) */};

  return (
    <form>
      <div>
        <label>
          Enter your name
          <input type="text" name="contactedBy" onChange={handleChange} />
        </label>
      </div>
      <div>
        <label>
          Enter your message
          <input type="text" name="message" onChange={handleChange} />
        </label>
      </div>
    </form>
  )
}

6

u/[deleted] Jul 28 '19

This is as far as I got before getting utterly lost in HOCs:

function ContactUs(props) {

  const handleChange = (e) => {}

  return View('form')
    ([View('div')
      (View('label')
        (
          ['Enter your name',
          View('input', { type:'text', name:'contactedBy', onChange:handleChange })]
        )
      ),
      View('div')
        (View('label')
          (
            ['Enter your name'],
            View('input', {type:'text', name:'message', onChange:handleChange })
          )
        )
    ])
}

4

u/[deleted] Jul 28 '19

Yes, this is right. Since its all JS functions, it enables more compositional style. So using HOCs is encouraged. Using deeply nested structures with the `View` primitive is only slightly more usable than `React.createElement` or `h`.

3

u/[deleted] Jul 28 '19

Sure, I'd do something like this:

const Form = View("form");
const Field = (label, props) => {
  return View("div)(
    View("label")(
      label, 
      View("input, { type: "text", ...props })()
  )
};

function ContactUs(props) {
  const handleChange = (e) => { };
  
  return Form(
    Field("Enter your name")
      .set({ name: "contactedBy", onChange: handleChange }),
    Field("Enter your message")
      .set({ name: "message", onChange: handleChange })
  );
}

5

u/vxnlol Jul 28 '19

I fail to see how this is easier to read, but it's a cool idea. Good work.

2

u/[deleted] Jul 28 '19

Thanks. I can understand why it seems less legible. It requires more functional components before things are as or more legible than JSX (maybe this is personal preference?). The main goal is something that doesn’t carry all the baggage that using Babel transpilation does

1

u/[deleted] Jul 28 '19

Ok, looks like I was close, but this is obviously a lot cleaner than my first attempt. Thanks!

1

u/[deleted] Jul 28 '19

You’re welcome! Thank you for checking it out and caring enough to ask! I’ll work on adding more examples so this is clearer for the next dev

4

u/Aeron91 Jul 28 '19

First I want to say, this is pretty neat! I think it would be pretty fun to try to write a wrapper around React that changes the way it works.

I don't really see this as something that should be adopted for real-world use though. The primary use-cases I see are (inspired by your 'Motivations' section in your readme):

  1. Beginners who don't want to open a command line.

The hardest part about this is installing node. Then all you need to get started are 3 commands:

npx create-react-app my-app
cd my-app
npm start

Plus, if you're going to be working with JavaScript on any largish project, npm is very useful to know how to use.

And there's always CodeSandbox too if you really don't want to deal with the command line.

2. Beginners to React who are more familiar with UI frameworks more similar to SwiftUI.

This kinda feels like an excuse to not leave your comfort zone and really grow by learning the tool you're working with. I'm not saying that you are making that excuse (I'm sure you had to learn quite a bit of React to be able to make this library), but someone else who sees this library and decides to use it.

From a readability standpoint I understand the friction of having to learn a new syntax. I've totally looked at libraries like SwiftUI before and thought, "Man, I wish they had a syntax more like jsx, because that would be easier to read and use!" I think it's more about what you're familiar with rather than one being inherently more readable than the other.

3. Sprinkling some react into a JavaScript-light website.

I see this as the most viable use-case. It is a little more ergonomic than directly using createElement.

Other Notes

One decision you made in particular bugs me. Correct me if I'm wrong, but the example makes it look like you could do this:

// Contrived example
const SubmitButton = (onClick, props) =>
View('button')(props.alternateLabel || 'Submit')
.set({ onClick });

// Usage
SubmitButton(handleClick)
.set({ alternateLabel: 'Send' });
```

So we have our primary-ish props passed in directly as arguments and then we have some other props that we can use with `set`. I think the reason this bugs me is that it isn't how React actually works. I see how that can be a useful tool in a UI framework in general, but it doesn't seem like it belongs in React.

And since I'm seeing the primary use cases being people new to React, it obfuscates how React actually works and presents a barrier when someone decides, "Now it's time to learn React for real".

---

So this got a lot longer than I expected it to, but that's my feedback. Overall, it's a cool project. :)

2

u/[deleted] Jul 28 '19 edited Jul 28 '19

Thank you so much for the thoughtful feedback. You make a lot of really great points. This was an idea that struck me and I mostly want to see if it’s viable. As you say, there are realistic challenges and I’m not sure if this works or is realistic for a production app but I’d like to think it’s perfect for prototyping, small projects, or quick hacks.

As for your gripe with using props I think you’d be pleased to know View does allow for assigning the props object upfront:

cons Button = (onClick, props) => View(“button”, { onClick, ...props });

And then calling Button(clickHandler, { id: “myButton” })(“My Button”) would produce your Button element.

2

u/AcidNoX Jul 28 '19

Was flutter your inspiration for this?

1

u/[deleted] Jul 28 '19

Flutter is really cool but the main inspiration was SwiftUI.

2

u/AcidNoX Jul 28 '19

Ah right - yeah SwiftUI is looking great too!

Really like what you’ve done here - keep it up, I look forward to seeing where it goes 👍🏻

1

u/[deleted] Jul 28 '19

Thanks for the encouragement!

1

u/[deleted] Jul 28 '19

Hi /r/reactjs!

I'm the author of ScriptUI. I whipped it up over the last few weekends as a proof of concept. I'm looking for feedback on whether you'd use something like this. I hope it helps make starting projects easier.

Thanks for reading!

4

u/friendshrimp Jul 28 '19

One thing that JSX gives us is named properties. I see this being useful if you are only passing a few props but as soon as you pass more than a few you’d have a confusing looking list of Paramus passed to a function.

1

u/[deleted] Jul 28 '19

That's a great point! Thanks for checking it out. I like to think there's still room for this through the use of an object literal or by leveraging modifiers.

For example:

// Object
const Button => ({ label, onClick }) => View("button", { onClick })(label);

// Modifier
const Button => ({ label, onClick }) => View("button")(label).set({ onClick });

// Custom Modifier for onClick is possible too
const Button => ({ label, onClick }) => View("button")(label).onClick(onClick);

// JSX
const Button => ({ label, onClick }) => <button onClick={onClick}>{label}</button>;

0

u/[deleted] Jul 28 '19

[deleted]

1

u/[deleted] Jul 28 '19

Good question! Thanks for checking this out. I don’t have a bunch of examples but I see how that could be helpful.

The friction is in the required tooling to use JSX. Node, npm, Babel. Without that tooling, you can use React.createElement. But that’s too long so you’ll need some alias. const h = React.createElement but this gets noisy because your element type, props, and children are all jammed into a single function call. So the abstraction is meant to break up the component definition more cleanly. This is inspired by how SwiftUI defines UI.

3

u/DeadPlutonium Jul 28 '19

Lotta respect for building a mini-API or new approach to solve tooling difficulties, must have been a good project to learn from if nothing else!

1

u/ibasiba Jul 28 '19

Can we use this with Styled Components?

2

u/[deleted] Jul 28 '19 edited Jul 28 '19

Not at this time. It’s a proof of concept so I can learn if it’s a good idea and how to improve it. Right now you need to use Emotion which is very similar to Styled Components. This allows me to create modifiers which apply styles to an element:

const Button => 
  View("button")("My button")
    .color("white")
    .background("red")
    .radius(".25em")
    .border("none");

Each of these (color, radius, etc.) is a modifier in ScriptUI which will change the props. In this case, they apply a class from Emotion with the style you defined. You could use .css(styleObject) to pass any styles and apply it as a class too.

I intend to package a slim version that doesn't depend on emotion and allows for more broad use with other style systems. The goal here is to minimize time to development and so building it in as a requirement made sense to achieve this kind of interface.

-2

u/Shade-73 Jul 28 '19

If you dont want to use JSX why use react?

2

u/[deleted] Jul 28 '19

JSX != React.

React has so many benefits that have nothing to do with JSX. JSX requires tooling that gets in the way when you’re just trying to build something. You shouldn’t need a terminal to build a web app.

0

u/Shade-73 Jul 28 '19

I never said its the same... But its one of its core features so why build a whole thing just not to use it

1

u/[deleted] Jul 28 '19

Because it isn’t a core feature. It’s an extra tool. The React library doesn’t contain JSX. Not using JSX means not having to install node, npm, or Babel just to start writing your app

0

u/[deleted] Jul 28 '19

[deleted]

1

u/[deleted] Jul 28 '19

Agreed! It’s a triumph over older ways of defining UI. But it can be a lot to learn for beginners to get started using it. So I wanted to try to see if a different, JS native syntax could be usable. Hopefully it lowers the barrier to entry. Maybe it’s easier for prototyping or quickly building stuff. It’s experimental.