![]() ![]() ![]() Let’s create the Greeter hook that is associated with that div. Now, when we head to we should see… not much yet. We also explicitly instruct LiveView to ignore updates for this element, since React does its own management of them. Notice how we attach a phx-hook attribute to it, which will be used by LiveView to interact with the component. This div element will be where our React component will live. Add the following controller: # lib/counters_web/controllers/home_live.exĪnd finally the view’s template (since we don’t have a render/1 function): # lib/counters_web/controllers/home_ Right after the index route for PageController. In our router file, add # lib/counters_web/router.ex #PHOENIX LIVEVIEW INSTALL#Just cd into the assets folder and run: npm install -save also install the type definitions, so we can use TypeScript properly: npm install -save-dev sorted, moving on to the LiveView hook. Once the app is generated and the DB created, let’s make sure mix phx.server works: Yep, all good Installing ReactĪdding React to our app is easy-peasy. Let’s create a new Phoenix app with PostgreSQL as DB and UUIDs as keys: mix phx.new counters -database postgres -binary-id We’ll be using Phoenix v1.6 and React v17 - v18 is out already, but is still new enough for me to get away with using the “old” one for this post. This post is a merge of sorts of this repo and this article, which had 90% of the answers. The LiveView hook mechanism is described in LiveView’s docs. #PHOENIX LIVEVIEW FULL#We’re not trying to have a full blown React app serve as our frontend and communicating with a Phoenix backend that serves no HTML. The desired end result is to be able to add an HTML element to a LiveView, associate it with a LiveView hook (not a React hook, but good luck searching for the former without the latter all over the results □) and have that LiveView hook control the lifecycle of the React component as a separate standalone app within your view. It’s perfect to help build interaction-heavy frontends to Phoenix apps, and it doesn’t have to be too complicated - especially now that esbuild has replaced Webpack as the builder of choice for Phoenix. React was what made me finally enjoy the little bits of frontend work I do now and again. Since taking the frontend world by storm in 2013, a lot of libs, blog posts and videos have been published by an enthusiasmic community. Thankfully, there’s a tool we can tap into for which an enormous amount of code has already been written - React. However, some projects still need heavier components with richer behaviors than what LiveView can easily deliver. Phoenix’s LiveView is great, and has drastically reduced the need for client-side Javascript code for basic use cases in Phoenix apps. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |