How-to guide: Server-render TSX components using Preact #3913
davidharting
started this conversation in
Show and tell
Replies: 2 comments 2 replies
-
Love this approach. I do see the benefit of type safety (as you mentioned) when using TSX on the server. I mainly have two concerns around it.
Good work on this 💪 |
Beta Was this translation helpful? Give feedback.
2 replies
-
@thetutlage started some interesting discussion on a similar topic here: https://twitter.com/AmanVirk1/status/1672848121292783616?s=20 |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Summary
Hello Adonis community!
My background is in React. I really enjoy the component model of React. JSX feels ergonomic to me. I especially love that with TSX you get:
I love this, but I also love the simplicity of keeping everything on the server (e.g., Inertia has more moving parts than I wanted). So I wondered: Can I simply render TSX components to HTML strings and serve those up? You can, and it was easier to setup than I expected.
I have a demo repo here: https://github.com/davidharting/adonisjs-preact-ssr. I walk through the pieces below.
This could be better organized, but I tried to do this in as few files as possible. Note, that there is no special build step, just a tweak to the tsconfig - TypeScript natively supports compiling TSX to js.
Code
You can check out the repo, but I also compile the highlights here.
Install Preact
tsconfig.json
Add these lines, per the Preact TypeScript guide.
Routing works normally
Controller logic with TSX component and rendering defined inside
This is
app/Controllers/Http/HomeController.tsx
In production, I would separate out the
HomePage
TSX component into its own fileI would also define the rendering utility in its own file, and perhaps add it to Context
Extending this for interactivity
I would recommend using Unpoly or htmx if you need to achieve client-side interactivity. This way, you can continue to keep all application logic on the server and keep the straightforward model of serving HTML.
With this model, all TSX components are rendered on the server. The components are not sent to the frontend - just the rendered HTML.
If you prefer to render components on the client, or both client and server, for your project - then Inertia will be a better fit.
Beta Was this translation helpful? Give feedback.
All reactions