Can I use react in some view of my laravel website

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x