Can I use react in some view of my laravel website

Viewed 272

I have a laravel website that is currently live and is using blade template for the views and I am thinking of using react JS in some views.

I want to know if it's possible to use react in some views while still having the blade template rendering some views.

OR do I have to rewrite the whole website in react for this to work.

1 Answers

Ok here's some example code that might help you get started with React:

Write a test react app e.g. test.jsx in your resources/js (or .tsx if you're using typescript). It might look something like:

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import App from './App';

const root = document.getElementById('react-root');
if (root) {
  ReactDOM.render(
     <App />,
      root
  );
}

Here App is the React component root for the feature you are replacing.

You can add this in your webpack.mix.js file as well to transpile it independently or import it in your app.js (which is easier). However in the later case you are loading this code in all views and if there is another page with an element with id react-root there will be problems.

Your blade will now become:

@extends('layouts.index')
@section('content')
    <div id="react-root"></div>
@endsection

Of course here it is oversimplified. You can just replace only the part that has the feature you are transitioning with <div id="react-root"></div> and have react handle that part from then on.

You can also do this multiple times in a single .blade.php file by making multiple calls to ReactDOM.render on different root elements. React will be fully responsible for everything under the root elements it renders to and the rest of your code will continue to run as before. However be aware that code that relied on element selectors via e.g. jQuery should not be used to manipulate nodes that React manages as that may cause problems.

Related