aboutsummaryrefslogtreecommitdiff
path: root/docs/ecosystem/react.md
blob: c0904421a61b52e88204efcabd7a2e5aa1149fc1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
Bun supports `.jsx` and `.tsx` files out of the box. Bun's internal transpiler converts JSX syntax into vanilla JavaScript before execution.

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

console.log(<Component />);
```

Bun implements special logging for JSX to make debugging easier.

```bash
$ 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.

```tsx
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](/docs/api/http):

```tsx#ssr.tsx
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'},
    });
  },
});
```