Can I use react in some view of my laravel website - reactjs

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.

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

REACT import css and js files

My application needs to have two pages, one landing page and one admin page. Both pages use different themes. I could not integrate css and js files of these two pages in a single page application.
const jquery = require('mdbootstrap/js/jquery-1.11.3.min.js');
window.jQuery = jquery;
window.$ = jquery;
require('mdbootstrap/css/bootstrap.min.css');
require('template/homePage/js/plugins/owl-carousel/owl.carousel.css');
require('template/homePage/js/plugins/owl-carousel/owl.theme.css');
require('template/homePage/js/plugins/owl-carousel/owl.transitions.css');
require('template/homePage/css/animate.css');
require('template/homePage/js/plugins/YouTube_PopUp-master/YouTubePopUp.css');
require('template/homePage/css/preloader.css');
require('template/homePage/css/style.css');
require('mdbootstrap/js/popper.min.js');
require('mdbootstrap/js/bootstrap.min');
require('template/homePage/js/plugins/vivid-icons');
require('template/homePage/js/plugins/owl-carousel/owl.carousel.js');
require('template/homePage/js/plugins/YouTube_PopUp-master/YouTubePopUp.jquery.js');
require('template/homePage/js/plugins/wow/wow.js');
require('template/homePage/js/plugins/jquery.easing.min.js');
require('template/homePage/js/main');
this sample import not good work. And I need outside link css and js.
I have two problem one of them is $(...).scrollspy is not a function
other WOW is not a function.
None of them work in sequence.
When you want to import resources into your React app, you use imports like this:
// Import with variable assignation
import logo from './logo.png';
// Import without variable assignation
import './css/index.css'
You can read more about this in the create-react-app documentation:
https://create-react-app.dev/docs/adding-images-fonts-and-files/
You can read more about ES7 imports here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
I see what you're trying to do is to add libraries and resources to your app component, like if were a common html file, you can't do that in React , you need to find an implementation.
It is not recommended to use jQuery with React, because you use jQuery to write code in a simple and fast way to create complex implementations, now those complex implementations can be made with just React and JS, that is what React is designed for.
Now I understand that you might want to use jQuery even do is not that recommendend, so here is a link where you can get jQuery to install it as a plugin for your React app
https://www.npmjs.com/package/jquery
You would be able to import it to your component like this:
import $ from "jquery";
To use Bootstrap in your React app you check out the documentation of an implementation of Bootstrap for React, react-bootstrap:
https://react-bootstrap.github.io/getting-started/introduction

Embed react component into website without Iframes

my company wants to create a react component which is going to render a google maps frame, a search field and a result list. Basically to search, see results and see them on the map.
Today the component is created but we're using a lot different libs like react-router, react-redux, axios, etc.
We want to find out a way to embed our component to another websites in a simple way without using iframes(if possible). Ideally a solution where we could just ask for our clients to add a div with a specific id and our script tab.
Any ideas how to solve it?
Thank so much.
In this situation, I'd suggest having Webpack bundle your component with whatever dependencies you need into a standalone js file. Then rather than using a typical app.js or index.js file that attaches an app to a body or div tag like create-react-app does, specifically use ReactDOM to render your component to a specific div based on ID. That way they just include your file and make sure they have the div with the ID and it'll take care of the rest. I've done something similar at a couple different jobs.
import ReactDOM from 'react-dom';
import MyComponent from 'my-component.js';
ReactDOM.render(<MyComponent />, '#my-div');
Besides that it's just tinkering with Webpack.
The consumer needs to tag an HTML element with an identifier in this case a class name representing a certain type of widget.
<div class="ray_widget"></div>
Then in the root of our react application src/index.tsx or jsx
We find all elements that are tagged and render react applications on it.
const WidgetDivs = document.querySelectorAll('.ray_widget')
WidgetDivs.forEach(divElement => {
const root = ReactDOM.createRoot(divElement);
root.render(
<React.StrictMode>
<Widget divElement={divElement} />
</React.StrictMode>
);
})
You then bundle your application and the customer needs to include the script on their website
<script src="https://your-react-app-bundle-cdn/index.js" type="text/javascript"></script>
Resource:
Embed React application without an iframe full post

Setting up webpack to export to set folder

I'm working on an old project still running jquery for frontend, java spring for the backend, and maven for building. I've been asked by my boss to introduce react into the stack so we can toy around with converting some of the pages.
My goal is to not impact the existing implementation to heavily and instead output the result of webpack into a defined directory. This way I can just point the backend at that location for pathing.
So far I have an apps folder in my workspace that contains all my react stuff that works on its own. This was generated using 'npx create-react-app folderName'.
I've somewhat read up on how to set the export but am generally confused. As a lot of resources I've found assume a new setup or a replacement of an existing setup. While I'm looking to only replace a single page currently.
I don't think create-react-app is the right tool here, since you don't create a complete application with React but incrementally add React code. I would suggest using Webpack on its own. This makes your application cleaner and easier to maintain with your other code.
If you want to keep your React code separate from your existing code you can create a library based on webpack's Authoring Libraries Guide. You can than render your components with ReactDOM.render() (Docs). Note that you can call this function (almost) unlimited times on one page which allows you to partially replace your existing code.
Replacing a page then means to create a root DOM element and call the render function:
<!-- page.html -->
<html>
<head></head>
<body>
<!-- more html -->
<div id="page-root" />
<!-- more html -->
</body>
</html>
import React from 'react'
import ReactDOM from 'react-dom'
import Page from './routes/YourPageComponent'
ReactDOM.render(<Page />, document.getElementById('page-root'));
The previous code means that you render your code in the new code which is transpiled by your webpack loaders (e.g. Babel-Loader, Typescript-Loader). If you want to render the code in the existing code, look at the Doc's about Webpack Libraries to export render functions into a global context. The following scripts are an example out of my head.
// components/PageExampleComponent.jsx
import React from 'react';
export default function({pageTitle="example"}){
return <div>
<h1>{pageTitle}</h1>
</div>
}
// libary/index.js
import PageExampleComponent from './components/PageExampleComponent';
export const MyLibrary = {
PageExampleComponent
}
The previous code requires the following (partial) Webpack config to export MyLibrary:
module.exports = {
//...
output: {
library: 'MyLibrary',
// based on a fast look into the docs, I think the following are optional:
libraryTarget: 'window',
libraryExport: 'default'
}
};
To render a component of this library, you need React and ReactDOM as scripts in your website - and of course your own library script. You can than call ReactDOM.render() in plain JavaScript:
ReactDOM.render(
React.createElement(window.MyLibrary.PageExampleComponent),
document.getElementById('page-root')
Another idea would be to move everything into Webpack. This might be easier, as you don't have barriers of different Javascript-Versions and dialects (e.g. with and without JSX support). You can even separate your jQuery code and your React code by using two entry points:
module.exports = {
//...
entry: {
oldCode: './src/jqueryIndex.js',
replacement: './src/reactIndex.js'
},
output: {
filename: "[name].js"
}
};

How to import React from global variable?

I have a special scenario. One web application is built upon React. Another JavaScript utility is on React, but that utility is loaded by script tag. So, the application and the utility is built isolatedly. As a result, both the web application bundle file and utility bundle file have React built inside.
Now, we want to make them share one copy of React. It is preferred to export React as global variable in web application code(e.g. global.React) so that the utility can use it directly.
The code in utility is still like below. Hopefully, webpack can ignore it and import React from global.React.
import React from 'react';
import ReactDOM from 'react-dom';
The question is: how to config webpack to tell the utiltiy not to bundle React?
Tested with some non-React application:
in index.html import React from CDN, this will define global React.
<script crossorigin src="https://unpkg.com/react#16/umd/react.production.min.js"></script>
somewhere in application doing as below, resolves to React instance:
declare var React;
console.log('React is ', React);
So if your first bundle, registers React globally, you may use it.
Just keep in mind, that it considered as bad practice to import from global like this. It beats whole concept of webpack's modularity. For instance, if your first module, upgrades to some backward incompatible version of React, your second module will break eventually as well.
For small projects, might be ok.

Is there any difference between React.render() and ReactDOM.render()?

I have noticed that some of the places in articles they have used React.render() and some of the places ReactDOM.render(). Is there any specific difference between these two?
This is a very recent change introduced with 0.14. They split up React into a core library and the DOM adapter. Rendering is now done via ReactDOM.render.
https://facebook.github.io/react/blog/2015/10/07/react-v0.14.html
React.render has been deprecated as of React 0.14. With packages like react-native, react-art, react-canvas, and react-three, it is clear that the beauty and essence of React has nothing to do with browsers or the DOM.
To make this more clear and to make it easier to build more environments that React can render to, the main react package has been split into two: react and react-dom.
This paves the way to writing components that can be shared between the web version of React and React Native.
The react package contains React.createElement, .createClass, .Component, .PropTypes, .Children, and the other helpers related to elements and component classes. Think of these as the isomorphic or universal helpers that you need to build components.
The react-dom package has ReactDOM.render, .unmountComponentAtNode, and .findDOMNode.
React.render has been deprecated since React 0.14. React diverged into two separate libraries. The core library knows how to work with React components, nest them together and so on, but to take the component and render it to the DOM is a separate library called ReactDOM. So to render a component, you don't use React you use ReactDOM.
import React from 'react';
import ReactDOM from 'react-dom';
Then you would apply it like so:
ReactDOM.render(App);
If you try to run it like that, back then you would probably have gotten an error that says:
Invalid component element. Instead of passing a component class, make sure to instantiate it by passing it to React.createElement.
If you get that error, it's a bit cryptic, think of the following function below is creating an instance of a component to the DOM:
const App = function() {
return <div>Howdy!</div>;
}
I passed App as a class to ReactDOM.render() and not an instance of the component. So it's saying please ensure you make an instance of the component and then pass it, or we need to instantiate it and then pass it to the DOM.
So you would fix it by passing an instance like so:
ReactDOM.render(<App />);
So that would create an instance of App and pass it to ReactDOM.render() but you would not be quite there yet as you would probably have gotten the following error message:
Target container is not a DOM element.
So React is saying I am trying to render this but I don't know where to render it to because ReactDOM takes a second argument which is a reference to an existing DOM node on the page. When you render this <App /> component, insert that HTML into this element that already exists in our HTML document. You would go to your index.html file and find the div with class="container" or whatever it is and that is the root node. All we have to do is pass a reference to that container like so:
ReactDOM.render(<App />, document.querySelector('.container'));
Then you will get the component rendering to the screen. And lastly, five years ago we got ES6 syntax so that App component from above could be rewritten like so:
const App = () => {
return <div>Howdy!</div>;
}
So using a fat arrow like that is identical to using the function keyword.

Resources