Make React Component available as a Widget - reactjs

I have a complicated React app (includes authentication to render certain components, etc) and there is a particular component, a date picker, which I would like other users to embed on their website as a Widget a la Google maps (<script src="my_widget"></script>).
I am already successfully sharing it as an iFrame, but I would like to learn how to do it as a 'proper' widget. Most of the solutions I found on SO were not to my understanding capabilities, perhaps I am pointed to a more noob solution.
FYI, I am using the create-react-app boilerplate code to load the React app:
ReactDOM.render(
<App />,
document.querySelector("#root")
);

You can create your react-app as it is. There are 2 more things that you'll need to make it work.
Provide a way to load or render your app on demand by the host page. For example rather than calling ReactDOM.render(<App />, document.querySelector("#root")); directly in the main app you can add a method like this:
const loadApp = (targetElement) => {
ReactDOM.render(<App />, targetElement);
};
You can expose this method using a global variable like this.
window.reactWidget.load = loadApp;
After that you'll need to create a JS snippet, which can load your bundled javascript file and call this function once the file is loaded from the network.
window.reactWidget.load(document.querySelector(#whatever'));

Related

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.
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.

Can't we inject component directly to App.js?

I am newbie to web development.After I had finished html,css and js(basic things) I recently have started learning react js. On my first project setup src folder I see index.js and app.js files. Why we need index.js files here? Can't we inject component directly to App.js?
index is generally used to say communicate _this is the highest level within this directory/hiearchy. Index is the entry point to your application where it's bootstrapped in the DOM. App is just a component like any other component. You could call it anything, e.g., Root, ComponentNotNamedApp, etc.
You don't need both, but it keeps the index file clean without adding in a bunch of component code. In App, you may be wrapping things with contexts, them providers, adding in other components, etc.
My app uses redux, so all that's in index is this,
ReactDOM.render(
// redux stuff
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)

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

Using React in existing web forms applications

I am having trouble understanding on how to add react to existing application.
From React official documentation and from multiple blogs I read I am very confused by now.
In my case I have an application written in web forms but acting as SPA and uses web methods and not native post backs.
I use jQuery in general on client side and call web methods with ajax calls and everything works fine with that approach.
Recently I started to dive into React and have a good understanding with concept and coding but not in deployment.
I want to start rewriting the current application by adding React components to existing site views and I don't understand what
is the correct approach. So the questions are:
Can React be used without transpiling? Is it the correct way to go?
What scripts should I include in output html if at all? I tried the
create-react-app, but this is a full template and currently I don't
think I need that.
For getting started with you just need to install, react & react-dom. Thats it. Start creating components and render with :
class Hello extends React.Component {
render() {
return React.createElement('div', null, `Hello ${this.props.toWhat}`);
}
}
ReactDOM.render(
React.createElement(Hello, {toWhat: 'World'}, null),
document.getElementById('root')
);
But writing react components without JSX is not ideally preferred, hence you might need babel-preset-react to transpile JSX to JS. That too is optional if you stick to writing React without JSX. The same code above can be written in JSX as :
class Hello extends React.Component {
render() {
return <div>Hello {this.props.toWhat}</div>;
}
}
ReactDOM.render(
<Hello toWhat="World" />,
document.getElementById('root')
);
Other than that you do not need anything to get started.

Is node js and JSX required for React JS

We have chosen the react JS 0.14.8 for front end because it supports IE 8 browser but Is Node JS or JSX is necessary for React JS development or we can create components without Node JS or Jsx
Yes you can create ReactJs app without nodejs and jsx.
But why you should use JSX?
JSX provides a very clean way to declare your UI component.
You can use your familiar html syntax to declare your user interface.
JSX gets trans-piled and converted to light weight objects representing ui elements.
e.g
You can use following way to declare a react js via
1.jsx
const App = () => {
return (
<div><h1>Welcome to React</h1></div>
);
}
or
2.without jsx
const App = function App() {
return React.createElement(
"div",
null,
React.createElement(
"h1",
null,
"Welcome to React"
)
);
};
You can guess which one is easy to write.
Why should I use nodejs to build browser projects?
nodejs is never required for running websites on browser.
But nodejs ecosystem provides you thousands of npm modules to use in your projects without reinventing them just for your projects.
Without nodejs you could have used cdn providers and added <script> tag to use any library. But with the use of module bundlers and static assets generator such as browserify and webpack you can leverage the powser of nodejs ecosystem directly in your web project( which does not require nodejs runtime environment but rather run in browser).
Below snippet use <script> tag to make reactjs available without nodejs.
const App = () => {
return (
<div><h1>Welcome to React</h1></div>
);
}
ReactDOM.render(<App />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app">
</div>
Is node js required for React JS?
Let me split the answer into 2 parts:
In Production:
Server Side: Not needed unless you are using Node.js to create a web server and server your ReactJS files.
Client Side: Only browser is enough.
In development:
Server Side: Needed to download react libraries and other dependencies using NPM. Needed by webpack to create production bundles.
Client Side: Only browser is enough.
Is JSX required for React JS?
Developer can use HTML tags directly inside javascript if JSX(javascript + XML tags) is used. otherwise it becomes difficult to write code as well as to understand the code.
Hope this answer helps, Thank you
They're not strict requirements; you can include react with a script tag and use React.createElement.
That said, almost everyone uses node.js for development tooling and uses jsx. You can use any language for your api server, but you'll use a node.js server in development most of the time.
Usage:
require('node-jsx').install()
If you want to use a different extension, do:
require('node-jsx').install({extension: '.jsx'})
If you want to couple with an additional transform (such as CoffeeScript), do:
var coffee = require('coffee-script');
require('node-jsx').install({
extension: '.coffee',
additionalTransform: function(src) {
return coffee.compile(src, {
'bare': true
});
}
});
If you want to use ES6 transforms available in the JSX tool
require('node-jsx').install({harmony: true})

Resources