LiveReact is a powerful library that seamlessly integrates React components with Phoenix LiveView. It allows you to use React components within your LiveView applications, combining the best of both worlds.
- Easy integration of React components in Phoenix LiveView
- Bi-directional communication between LiveView and React components
- Automatic prop and state management
- Error boundary for React components
- Simple setup process
If available in Hex, the package can be installed
by adding live_react to your list of dependencies in mix.exs:
defdepsdo[{:live_react,"~> 0.1.0"}]endThen run mix deps.get to fetch the dependency.
To set up LiveReact in your Phoenix project, run the following mix task:
mix live_react.setupThis task will:
- Update your config files
- Add necessary JavaScript files and React components
- Update your package.json
- Add a sample LiveView using LiveReact
After running the setup task, follow these steps:
- Run
npm installin yourassetsdirectory to install React and other dependencies. - Add the following to your
router.ex:
live"/live_react_example",LiveReactLive- Start your Phoenix server and visit
/live_react_exampleto see LiveReact in action!
To use a React component in your LiveView, use the react function component provided by LiveReact:
importLiveReact.Componentdefrender(assigns)do~H"""<.reactid="hello-world"component="HelloWorld"props={%{initialCount: @count}}handle_event="increment"/>"""endReact component
importReact,{useState,useEffect}from"react";constHelloWorld=({ initialCount, pushEvent })=>{const[count,setCount]=useState(initialCount);useEffect(()=>{setCount(initialCount);},[initialCount]);consthandleIncrement=()=>{constnewCount=count+1;setCount(newCount);pushEvent("increment",{count: newCount});};return(<div><h2>Hello from React!</h2><p>Count: {count}</p><buttononClick={handleIncrement}>Increment</button></div>);};exportdefaultHelloWorld;To handle events from the React component, define a handle_event function in your LiveView:
defhandle_event("increment",%{"count"=>count},socket)do{:noreply,assign(socket,count: count)}endLiveReact uses esbuild for bundling React components. Add the following configuration to your config/config.exs:
config:esbuild,react: [args: ~w(js/app.js --bundle --target=es2016 --outdir=../priv/static/assets --external:/fonts/* --external:/images/* --loader:.js=jsx),cd: Path.expand("../assets",__DIR__),env: %{"NODE_PATH"=>Path.expand("../deps",__DIR__)}]And update your config/dev.exs:
config:your_app,YourAppWeb.Endpoint,watchers: [esbuild: {Esbuild,:install_and_run,[:react,~w(--sourcemap=inline --watch)]}]Contributions are welcome! Please feel free to submit a Pull Request.
LiveReact is released under the MIT License. See the LICENSE file for details.