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.
Related
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
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'));
How to merge node_module, project dependencies, of both Svelte and ReactJs?
I've seen guides showing how to include ReactJS file into a Svelte app
<SvelteComponent this={First} {...this.props}/>
That produces the following error:
Constructor is not a Constructor error
here is an example of including a svelte component in react. It been written by Rich Harris author of svelte:
https://github.com/Rich-Harris/react-svelte
Svelte and React are not compatible to import and use the other framework component directly.
It is definitely possible to create a Svelte app inside of a React app or vice-versa though.
You would have to instantiate the app like normal inside of the other app. The Svelte docs show how you can bind a Svelte app to a DOM node, which you can include in a React component. Make sure you also add the DOM node inside of that component, such as <div id="svelte-app" />.
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.
We're on the decision on where to go on localization in react.js, surely there are ways to doing localization, but what would be your recommendation?
I tried yahoo's react-intl but to no avail:
var ReactIntl = require('react-intl') // we did npm install react-intl
// somewhere in the react component
render: function() {
return (<div><ReactIntl.Number>{600}</ReactIntl.Number></div>);
}
gives the error: Cannot read property '_mockedReactClassConstructor' of undefined
spent few hours try to resolve this error, still can't resolve -> give up
I tried l20n by mozilla but not sure if it'll work with react.js
wondering what would you suggest for react.js localization, thanks!
in response to my question. we decided not to use yahoo's react-intl but use i18next instead. Considering using something more stable and popular for our production is important.
what you can do is to initialize i18next at the root of your page, and pass that down through props. Do use a state to prevent page rendering before i18next is initialized.
there is now react-i18next https://github.com/i18next/react-i18next works with i18next >=2.0.0
it's been couple month from now. Perhaps there are more localisation modules out there. But if you wish to do something simple and bypass using so many modules (we only use essential modules lessen the load), here's the setup:
let's say we have a root page and login page (on our router setup, things are based on root page)
root
have a state called i18n (in getInitialState)
detect your language and init the i18n
set the object to i18n state
in render() use something like this
render: function() {
var route;
if (this.state.configLoaded && this.state.i18n) {
route = (
<RouteHandler i18n={this.state.i18n} onLanguageChange={this._languageChangedHandler} />
);
}
return (
<div>
<Loading />
{route}
</div>
);
}
and you pass i18n down through props. or if you wish, using mixins.
login
this.props.i18n.t('...')
I think maybe use FormattedNumber from React-Intl for your purpose.
Things to consider, if you use i18next that only gives you translations , not Times/Dates/Currency etc, you'll need additional libraries like Moment.js. React-Intl gives you it all.
Watch out for IE<9 , you'll have to have the Intl.js polyfill or polyfill service (https://cdn.polyfill.io/v2/docs/). I have found webpack to be problematic loading this polyfill.
Finally , with React-Router latest version see https://github.com/rackt/react-router/blob/master/UPGRADE_GUIDE.md
You'll probably find the section on RouteHandler worthwhile, use
{React.cloneElement(this.props.children, {someExtraProp: something })}
To pass your loacles/messages into views.
Hope that helps