How to use react-intl v2 + webpack to load locale file? - reactjs

I have a setup to use webpack to manage all my assets. it works fine. Now I plan to use react-intl version 2 to support multiple languages.
I have managed to make components defined in package 'react-intl' work,
import {IntlProvider, FormattedNumber, FormattedPlural} from 'react-intl';
class App extends Component {
constructor(props) {
super(props);
this.state = {
name : 'Eric',
unreadCount: 1000,
};
}
render() {
const {name, unreadCount} = this.state;
return (
<p>
Hello <b>{name}</b>, you have {' '}
<FormattedNumber value={unreadCount} /> {' '}
<FormattedPlural value={unreadCount}
one="message"
other="messages"
/>.
</p>
);
}
}
But I can't figure out what's the correct way to load locale file through webpack and refer them in component. Since the package has breaking upgrade recently, there is no much documentation about it either. the wiki page is empty for now
https://github.com/yahoo/react-intl/wiki
I wonder What's the correct way to do this?

xiopang,
I just wrote a webpack plugin based around the translations example from react-intl v2. Hopefully it works for you: https://gist.github.com/marr/95f7a8a3f5529e7e668048548198b9eb
the webpack config plugins then look like:
new TranslateWebpackPlugin(),
new HtmlWebpackPlugin({
template: 'index.hbs', // Load a custom template
inject: 'body', // Inject all scripts into the body
chunks: [ 'app' ],
app: true
}),
and index.hbs:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script>
window.App = <%= htmlWebpackPlugin.options.app %>
</script>
</head>
<body>
<div id="app"></div>
</body>
</html>

Related

How to implement client-side on ASP.NET CORE MVC project with RactJS Component

[EDIT]
Ok, i unstertood that, if i render my class in a div with id="root" using ReactDOM.render it work and i can use console.log().
But i need that this component, that is in a Razor pages, could be receive ,as props, some data of the Razor's Model. (for example a list of users). So, i decided to use #Html.React to load the component. But if i use this method, i can pass properties but console.log() doesn't work.
What should i do?
And, there is a way which i can use, in the razor pages, the component as "" ??
[EDIT]
i want to do something like that but the component are not showing anymore.
<div id="root">
<App/>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/remarkable/1.7.1/remarkable.min.js"></script>
<script src="#Url.Content("https://unpkg.com/#babel/standalone/babel.min.js")"></script>
<script src="#Url.Content("~/js/app.jsx")" type="text/babel"></script>
i have an ASP.NET CORE MVC project and i want that my Razor pages implement ReactJS component.
I can load the component App but when i tried to use console.log it doens't work. I figure out that is because the component load only on server side but i can't find a correct way to allow my client-side to access to component and use the js to print in the console a value that i want.
First solution i tried was by follow this link: https://reactjs.net/features/server-side-rendering.html
But when it says to add :
#Scripts.Render("~/bundles/main")
#Html.ReactInitJavaScript()
I have 2 problem:
don't foud #Script so i had to install WebOptimize..but now it says that cannot fine the Ihtml string
i don't have this '~/bundles/main', what is that file? i have to install packages?
with ReactInitJavaScript component is showen but in the inspector says that component is undefined and in the class cannot find React.Component
So, the value are showen but i can't access to console. What i have to insert in the code to enable the client-side??
_Layout.cshtml:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>#ViewData["Title"] - SportData</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<link rel="stylesheet" href="~/css/card.css" asp-append-version="true" />
</head>
<body>
<div class="container">
<main role="main" class="pb-3">
#RenderBody()
</main>
</div>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
#await RenderSectionAsync("Scripts", required: false)
</body>
</html>
Index.cshtml
#using Newtonsoft.Json;
#using SportData.Web.Models;
#using System.Web.Optimization;
#model SportContainer
#Html.React("App",new { Property1 = "value1", Property2 = "value2" })
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/remarkable/1.7.1/remarkable.min.js"></script>
#Scripts.Render("~/bundles/main")
#Html.ReactInitJavaScript()
App.jsx:
class App extends React.Component{
componentDidMount() {
console.log('hi')
}
render() {
console.log(this.props)
const { Property1, Property2 } = this.props
const handler = (event) => {
console.log(event);
}
return (
<div>
<button onClick={handler}> clicca </button>
{console.log(this.props)}
<p>Property1: {Property1}</p>
<p>Property2: {Property2}</p>
<div className="box">Sono un box</div>
</div>
);
}
}
Program.cs:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddMvc().AddRazorRuntimeCompilation();
//builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddReact();
builder.Services.AddHttpContextAccessor();
builder.Services.AddJsEngineSwitcher(option => option.DefaultEngineName = V8JsEngine.EngineName).AddV8();
var app = builder.Build();
// configure middleware
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseReact(config => {
config.AddScript("~/js/App.jsx");
});
ReactSiteConfiguration.Configuration.JsonSerializerSettings.ContractResolver = new DefaultContractResolver();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
you have to use react js with api this is way.because if you will use react js like this you cannot make rich ui and also issues with the packges but if you want to use like this so you have to use like this.
check here

Using CDN in React

I've installed React via NPM and I'm having difficulty using CDN. I included the CDN scripts in the ./public/index.html file but when I use it in any component, it doesn't recognize the third-party package that I'm trying to use.
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.min.js"></script>
Tried to use Axios but it doesn't work:
axios.post("https://burger-builder-c5a0d.firebaseio.com/orders.json", order)
.then(response=>{
alert("You ordered successfully!"); //shows an alert indicating a successful process
console.log(response); //sends results to the server
this.setState({
showModal: false, //closes the modal
loading:false,
purchasable: false
})
}).catch(error=>{
this.setState({
showModal: false,
purchasable: false,
loading: false
})
console.log(error);
})
Tried to use redux and it's also not being recognized
const reduxStore= redux.createStore;
const store = createStore();
Here's the error that I'm getting
Did you import the axios or redux package via require?
Like this:
const axios = require('axios');
EDIT
You're right. You don't even need to require something since you're importing from the CDN
I tried with the HTML boilerplate from the React.js documentation and imported the CDN from your source.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello World</title>
<script src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<!-- Don't use this in production: -->
<script src="https://unpkg.com/#babel/standalone/babel.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
function fetch() {
axios
.get("https://jsonplaceholder.typicode.com/todos/1")
.then(response => console.log(response.data));
}
ReactDOM.render(<h1>{fetch()}</h1>, document.getElementById("root"));
</script>
<!--
Note: this page is a great way to try React but it's not suitable for production.
It slowly compiles JSX with Babel in the browser and uses a large development build of React.
Read this section for a production-ready setup with JSX:
https://reactjs.org/docs/add-react-to-a-website.html#add-jsx-to-a-project
In a larger project, you can use an integrated toolchain that includes JSX instead:
https://reactjs.org/docs/create-a-new-react-app.html
You can also use React without JSX, in which case you can remove Babel:
https://reactjs.org/docs/react-without-jsx.html
-->
</body>
</html>
It seems you're trying to import Redux and Axios via CDNs, although they both are available as NPM packages.
Anyways, You can simply import any CDN script by using createElement() of ReactJs.
componentDidMount = () => {
const script = document.createElement("script");
script.src = "https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js";
script.async = true;
document.body.appendChild(script);
};

How to have react app in the HTML without npm start or similar commands

I'm kinda new to ReactJS and don't even know if it's possible but I want my react app to be working in the browser from the .html file. without the need for calling the server and have it, working, only that way. ( I don't mind having a server to serve it obviously) just need to be able to have by calling the .html file
the public/index.html file:
<head>
<meta charset="utf-8">
<script src="/my_library/my_library.min.js"></script> <!-- needed for the project in the same folder the index.html is -->
<title>Demo</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start`.
To create a production bundle, use `npm run build`.
-->
</body>
</html>
the index.js (in src folder):
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import App from './App';
import './index.css';
ReactDOM.render(
React.createElement(App),
document.getElementById('root')
);
The App.jsx in the src folder
import * as React from 'react';
import './App.css';
import { MyContainer } from './components/MyContainer/index';
class App extends React.Component {
render() {
return (
<div className={ 'App' }>
<header className={ 'App-header' }>
<h1 className={ 'App-title' }>
</h1>
</header>
<MyContainer />
</div>
);
}
}
export default App;
PS: I have been able to add React to my file... But this particular component that I want to add only works with NPM Start. and as you can see in the index.html file shown above is says
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
which is exactly what I aim to change. if any one can provide some guidance or help about this, would be much appreciated.
If you just want to use React within an HTML file within a browser maybe you could just include the React library with a script tag as well as your custom React scripts with script tags as well. Their documentation has a nice example of just using React within an HTML file. I created a Codebox with their sample example for this below where the like button is using react. However, if you want to use JSX syntax you will have to use Babel, to transpile JSX into native JavaScript, and link the library like such:
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
create_react_app gives you a lot of bells and whistles so you don't have to worry about setting up build configurations using tools such as webpack, babel, eslint, etc.. but this meant to give you a head start on building out an application so you can focus on the application itself and not configuration settings. Behind the scenes it's using webpack-dev-server to serve up your application, but for your use case I think it would be best to just add React as a script tag to an existing HTML page
'use strict';
const e = React.createElement;
class LikeButton extends React.Component {
constructor(props) {
super(props);
this.state = { liked: false };
}
render() {
if (this.state.liked) {
return 'You liked this.';
}
return e(
'button',
{ onClick: () => this.setState({ liked: true }) },
'Like'
);
}
}
const domContainer = document.querySelector('#like_button_container');
ReactDOM.render(e(LikeButton), domContainer);
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Add React in One Minute</title>
</head>
<body>
<h2>Add React in One Minute</h2>
<p>This page demonstrates using React with no build tooling.</p>
<p>React is loaded as a script tag.</p>
<!-- We will put our React component inside this div. -->
<div id="like_button_container"></div>
<!-- Load React. -->
<!-- Note: when deploying, replace "development.js" with "production.min.js". -->
<script src="https://unpkg.com/react#16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js" crossorigin></script>
<!-- Load our React component. -->
<script src="like_button.js"></script>
</body>
</html>
Hopefully that helps!

use Angular routing in AngularJS/Angular hybrid app reload all page

I am trying to make Angular routing in my AngularJS/Angular hybrid application.
I created app-routing.module.ts file :
import { ModuleWithProviders } from "#angular/core";
import { Routes, RouterModule, ExtraOptions } from '#angular/router';
import {SignInComponent} from "./modules/login/components/sign-in/sign-in.component";
import {ActivationComponent} from "./modules/login/components/activation/activation.component";
const routes: Routes = [
{
path: 'sign-in',
component: SignInComponent
},
{
path: 'activation',
component: ActivationComponent
},
{
path: '',
pathMatch: 'full',
redirectTo: '/activation'
},
{
path: '**',
pathMatch: 'full',
redirectTo: '/activation'
}
];
export const routingModule: ModuleWithProviders = RouterModule.forRoot(routes);
in app.module.ts I added routingModule to "imports" array and in app.component.html I added :
<button (click)="goto('sign-in')">go to home</button>
<button (click)="goto('activation')">go to product</button>
<router-outlet></router-outlet>
When insight by index.html i am using just Angular it works perfectly
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Angular</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>
But when I am adding my AngularJS code just adding
this.upgrade.bootstrap(document.body, ['app']);
my current Angular routing instead reload content of "router-outlet" tag, reloads completely the page. If I remove
this.upgrade.bootstrap(document.body, ['app']);
it works fine.
Does anybody had some similar issues and maybe someone can propose some scenario how to make Angular routing work appropriately insight hybrid AngularJS/Angular application?
Thanks
It looks like you have not configured the AngularJS and Angular Router in the correct way, please verify the below steps-
Default route (.otherwise) should be removed from AngularJS routing.
Implement the 'UrlHandlingStrategy' interface as a part of Angular router config settings to handle the routing for specific URLs. This will avoid the Angular router conflict with AngularJS router-
export class Ng1Ng2UrlHandlingStrategy implements UrlHandlingStrategy {
shouldProcessUrl(url: UrlTree): boolean {
return url.toString().startsWith('/ng/');
}
extract(url: UrlTree): UrlTree { return url; }
merge(newUrlPart: UrlTree, rawUrl: UrlTree): UrlTree { return newUrlPart; }
}
Add above class (Ng1Ng2UrlHandlingStrategy) as a provider in the root module for URL handling strategy-
providers: [
{ provide: UrlHandlingStrategy, useClass: Ng1Ng2UrlHandlingStrategy }
]
Add both AngularJS and Angular outlet/directive in the app component html
<router-outlet></router-outlet>
<div class="ng-view"></div>
Hash based routing will work but setUpLocationSync(upgrade) is required to support the html 5 based routing in the hybrid app. Please update the main.ts file like below-
upgrade.bootstrap(document.body, ['app']);
setUpLocationSync(upgrade);

No Error so is why my component not rendering?

I am brand spanking new to this React stuff and stumbling around trying to understand all of the moving parts. I have started a server with the webpack dev server and attempting to render my code to http://localhost:8080/ but to no avail. It's just a simple form component. There are more than likely many things wrong with how I have things set up, but again, still learning! Thanks for any help anyone can offer. I have an index.html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Practicing Components</title>
</head>
<body>
<div id="app"></div>
<script type='text/babel'></script>
</body>
</html>
This index.html file is rendering my main.js file:
import React from 'react';
import ReactDOM from 'react-dom';
class Main extends React.Component {
render() {
return (
<div>
<h1>Welcome to the Name Board!</h1>
<Form />
<Button />
</div>
);
}
}
class Form extends React.Component {
constructor(props) {
super(props);
this.state= {value: 'Please type your name.'};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
render() {
return (
<input type="text" value={this.state.value} onChange={this.handleChange} />
);
}
}
class Button extends React.Component {
render() {
return (
<button value="Submit">
</button>
);
}
}
ReactDOM.render(<Main />, document.getElementById('app'));
I've set up my module loaders and entry point and all that in my webpack.config.js:
var path = require("path");
module.exports = {
entry: {
app: ["./main.js"]
},
output: {
path: path.resolve(__dirname, "build"),
filename: "bundle.js"
},
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel',
exclude: /node_modules/,
query: {
cacheDirectory: true,
presets: ['react', 'es2015']
}
}
]
}
};
However, despite not having any error messages and my server being successfully connected, I am rendering nothing.
Looks like you're not even loading the bundle:
<script src="/build/bundle.js"></script>
It's not React. It's the HTML code. It doesn't seem to be telling the browser to load the bundle from anywhere, e.g. the <script> tag doesn't have an attribute src="/build/bundle.js".
So maybe to fix it, you'd have better luck after changing your HTML code to look like so?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Practicing Components</title>
</head>
<body>
<div id="app"></div>
<!-- See how "src" is now set to "app.bundle.js"? -->
<script src='/build/bundle.js'></script>
</body>
</html>

Resources