Files
bun.sh/docs/ecosystem/react.md
Colin McDonnell 9b6913e1a6 More/better docs for JSX, utils, binary data, streams, hashing, bun test, Bun.serve (#3005)
* WIP

* Updates

* Document deepEquals

* WIP

* Update typeS

* Update TLS docs for Bun.serve

* Update types for tls

* Draft binary data page. Add Streams page.

* Update test runner docs

* Add hashing, flesh out utils

* Grammar

* Update types

* Fix

* Add import.meta docs

* Tee
2023-05-29 11:49:51 -07:00

1.6 KiB

Bun supports .jsx and .tsx files out of the box. Bun's internal transpiler converts JSX syntax into vanilla JavaScript before execution.

function Component(props: {message: string}) {
  return (
    <body>
      <h1 style={{color: 'red'}}>{props.message}</h1>
    </body>
  );
}

console.log(<Component message="Hello world!" />);

Bun implements special logging for JSX to make debugging easier.

$ bun run react.tsx
<Component message="Hello world!" />

Prop punning

The Bun runtime also supports "prop punning" for JSX. This is a shorthand syntax useful for assigning a variable to a prop with the same name.

function Div(props: {className: string;}) {
  const {className} = props;

  // without punning
  return <div className={className} />;
  // with punning
  return <div {className} />;
}

Server-side rendering

To server-side render (SSR) React in an HTTP server:

import {renderToReadableStream} from 'react-dom/server';

function Component(props: {message: string}) {
  return (
    <body>
      <h1 style={{color: 'red'}}>{props.message}</h1>
    </body>
  );
}

Bun.serve({
  port: 4000,
  async fetch() {
    const stream = await renderToReadableStream(
      <Component message="Hello from server!" />
    );
    return new Response(stream, {
      headers: {'Content-Type': 'text/html'},
    });
  },
});

React 18.3 and later includes an SSR optimization that takes advantage of Bun's "direct" ReadableStream implementation.