How to read Spring Boot application.properties in ReactJs app? - reactjs

We have 2 configuration files: one is in our Spring Boot application (application.properties) and another in our ReactJs app (we use .env in create-react-app). It was decided to use Spring Boot application.properties also in ReactJs app. Can anyone please guide me how can I achieve this?
I have read about "properties-reader" and tried to use it, but I don't have webpack.config.js file in our ReactJs app.

Thymeleaf provides the easiest way to pass data from application.properties file to Javascript via the template (index.html) file.
Alternatively, it can be done using normal JSP also.
Here are the working examples:
Option 1: Thymeleaf
Step 1: Define the interesting data attributes as hidden elements in the index.html file
<div id="root"></div> ---> Div to be updated by react
....
<span id="myData" hidden></span>
<!-- Script to set variables through Thymeleaf -->
<script th:inline="javascript">
var myData = "[${myData}]]";
document.getElementById("myData").innerHTML = myData;
</script>
Important note:
Make sure that the same index.html file exists in the '/public' folder of Reactjs project as well as in the /src/main/resources/templates/ folder of the spring boot project.
Step 2: Use model.addAttribute() method in Spring Boot to invoke Thymeleaf for setting data in the index.html file
#GetMapping("/")
public String index(Model model) {
// Get the value of my.data from application.properties file
#Value("${my.data}")
private String myData;
// Call Thymeleaf to set the data value in the .html file
model.addAttribute("myData", myData);
return "index";
}
Step 3: Update the ReactJS code to read the interesting attribute using document.getElementById
let myData = document.getElementById("myData").innerHTML
More information:
https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#javascript-inlining
https://attacomsian.com/blog/thymeleaf-set-javascript-variable
Option 2: JSP
Step 1: Define the interesting data attributes as hidden elements in the index.jsp file
Location of index.jsp: src/main/webapp/WEB-INF/jsp/index.jsp
<!DOCTYPE html>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html lang="en">
<head>
<!-- Head section here -->
</head>
<body>
<!-- Div to be updated by react -->
<div id="root">
</div>
<!-- Include the interesting attribute as a hidden field -->
<span id="myData" hidden>${myData}</span>
</body>
</html>
Important note:
Make sure that the /public/index.html file of reactjs project has the same content (<body>...</body>) as that of the src/main/webapp/WEB-INF/jsp/index.jsp file of spring boot project)
Step 2: Use map.put() in Spring Boot controller to update data in JSP
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
#Controller
public class HomePageController{
// Read data from application.properties
#Value("${my.data}")
private String myData;
// Update data attributes of JSP using map.put
#GetMapping("/")
public String index( Map<String, Object> map ) {
map.put("myData", myData);
return "index";
}
}
Step 3: Update the ReactJS code to read the interesting attribute using document.getElementById
let myData = document.getElementById("myData").innerHTML
More information:
https://mkyong.com/spring-boot/spring-boot-hello-world-example-jsp/

Related

meta tag server side rendering

I am using react helmet and am a bit lost with regards to the server side rendering. If I view elements in google console I can see the title and meta description but when viewing the page source they are not there.
I am using a Node.js backend with express to create an API. The React app is just a frontend application which gets data from the Node.js API.
In React I simply have:
import { Helmet } from "react-helmet";
render() {
return(
<>
<Helmet>
<title>My site title</title>
<meta name="description" content="Helmet application" />
</Helmet>
</>
)
}
The direct link to the server side example shows some code which I don't really know what to do with. I think the word 'server' is throwing me off because I am thinking that I need to put some code on my Node.js server but perhaps that is not the case?
Indeed, Helmet.renderStatic() method will collect all tags corresponding to the page you are requesting.
If you want to see those tags on the server side as well (source code), you need to, in your server file:
Call const helmet = Helmet.renderStatic()
From helmet get helmet.title.toString() and helmet.meta.toString()
Append those to your HTML just like https://github.com/nfl/react-helmet#server-usage As string input describes.
Change index.html to index.php and use PHP in index.php after build. and create a file myMata.php move all old meta tags to myMata.php and make dynamic meta tags using PHP.
view-source:https://www.heinsoe.com
index.php
<html>
<head>
<?php include './myMata.php';?>
//more code
myMata.php
<?php
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$paths = (explode("/", $path));
if (isset($paths[1])) {
switch ($paths[1]) {
case 'blog':
?>
<title>dynamic title</title>
//..... other tag
<?php
break;
case 'contact':
?>
<title>contact</title>
//..... other tag
<?php
break;
default:
http_response_code(404);
break;
}
}
else{
?>
<title>Home</title>
//..... other tag
<?php
}
?>

Pass data from `index.html` to react components

I recently got started with web development. And I am stuck with sth that's probably a trivial problem. I am trying to figure out how I can pass data from my dynamically created index.html to my (typescript) react frontend (created via create-react-app).
Suppose we have a flask web server that, when the '/' resource is requested, gathers some initial user data, instantiates a page template with it and returns that page:
# flask webserver
from flask import Flask
from flask import render_template
app = Flask(__name__)
#app.route('/')
def index():
initial_user_data = {"foo":"bar",
"baz":"biz"}
return render_template('index.html', initial_data=initial_user_data)
if __name__ == '__main__':
app.run(debug=True)
For the sake of simplicity initial_user_data stores hard-coded data here. In my actual use case the dictionary gets populated with various user-specific data items that are read from files etc.
Next, let's assume index.html uses the initial_data.
<!DOCTYPE html>
<html lang="en">
<head>
...
<title>React App</title>
</head>
<body>
<script>
initial_data = {{initial_data | tojson}}
console.log(initial_data)
</script>
<div id="root"></div>
...
</body>
</html>
When we now start the webserver and open a browser to navigate to the page when can see the initial_data being logged to the browser's console output. So far, so good.
Now my problem: how can I pass initial_data to my (typescript) react components? Conceptually I want to do sth like this:
// App.tsx
import React from 'react';
const App: React.FC = () => {
// make use of 'initial_data'
const init_data = initial_data;
return (
<div ...
</div>
);
}
But yarn build will give me
Cannot find name 'initial_data'. TS2304
4 |
5 | const App: React.FC = () => {
> 6 | const init_data = initial_data;
| ^
7 | return (
8 | <div className="App">
9 | <header className="App-header">
How can I make initial_data accessible to my react components?
Edit: If this pattern of passing something from the index.html (that gets created on the backend when a clients connects) to my typescript react components is flawed then I'd also accept an answer that points me to the correct pattern in this case.
Something along the lines of (obviously just making sth up, just trying to illustrate what I mean)
Define a typescript data type that stores the user data that can be accessed from all your components
in your main react component use a life-cycle method like 'componendDidMount' to send a request to the backend to fetch the initial_data
When the response comes back store it in 1)
I'd accept an answer that adds shows some sample code for 1) 2) 3)
Many thanks for your help!
When you pass global variables inside a react component, it's always a better way to pass it using the window object.
In this case, you need to pass it as window.initial_data. This informs the linter and react that it's a global variable. As it is not defined inside the file.

How to pass Serverside parameter in ASP.Core to React?

I created a React/Typescript project with dotnet new "ASP.NET Core with React.js".
index.cshtml:
<div id="react-app"></div>
#section scripts {
<script src="~/dist/main.js" asp-append-version="true">
</script>
}
boot.tsx(shortened):
function renderApp() {
ReactDOM.render(
<AppContainer>
<BrowserRouter children={ routes } />
</AppContainer>,
document.getElementById('react-app')
);
}
renderApp();
if (module.hot) {
module.hot.accept('./routes', () => {
routes = require<typeof RoutesModule>('./routes').routes;
renderApp();
});
}
How can I pass ASP.Core generated information(the routes from the controllers) to my react/typescript code?
To use server-side rendering in your application, follow the following steps:
1 - Modify App_Start\ReactConfig.cs (for ASP.NET MVC 4 or 5) or Startup.cs (for ASP.NET Core) to reference your components:
namespace MyApp
{
public static class ReactConfig
{
public static void Configure()
{
ReactSiteConfiguration.Configuration = new ReactSiteConfiguration()
.AddScript("~/Scripts/HelloWorld.jsx");
}
}
}
This tells ReactJS.NET to load all the relevant JavaScript files server-side. The JavaScript files of all the components you want to load and all their dependencies should be included here.
2 - In your ASP.NET MVC view, call Html.React to render a component server-side, passing it the name of the component, and any required props.
#Html.React("HelloWorld", new
{
name = "Daniel"
})
3 - Call Html.ReactInitJavaScript at the bottom of the page (just above the ) to render initialisation scripts. Note that this does not load the JavaScript files for your components, it only renders the initialisation code.
<!-- Load all your scripts normally before calling ReactInitJavaScript -->
<!-- Assumes minification/combination is configured as per previous section -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react-dom.js"></script>
#Scripts.Render("~/bundles/main")
#Html.ReactInitJavaScript()
4 - Hit the page and admire the server-rendered beauty:
<div id="react1">
<div data-reactid=".2aubxk2hwsu" data-react-checksum="-1025167618">
<span data-reactid=".2aubxk2hwsu.0">Hello </span>
<span data-reactid=".2aubxk2hwsu.1">Daniel</span>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react-dom.js"></script>
<script src="/Scripts/HelloWorld.js"></script>
<script>ReactDOM.render(HelloWorld({"name":"Daniel"}), document.getElementById("react1"));</script>
The server-rendered HTML will automatically be reused by React client-side, meaning your initial render will be super fast.
If you encounter any errors with the JavaScript, you may want to temporarily disable server-side rendering in order to debug your components in your browser. You can do this by calling DisableServerSideRendering() in your ReactJS.NET config.
For a more in-depth example, take a look at the included sample application (React.Samples.Mvc4).
5 - Server-side only rendering
If there is no need to have a React application client side and you just want to use the server side rendering but without the React specific data attributes, call Html.React and pass serverOnly parameter as true.
#Html.React("HelloWorld", new
{
name = "Daniel"
}, serverOnly: true)
And the HTML will look like the one following which is a lot cleaner. In this case there is no need to load the React script or call the Html.ReactInitJavaScript() method.
<div id="react1">
<div>
<span>Hello </span>
<span>Daniel</span>
</div>
</div>

How to use __webpack_public_path__ variable in a Webpack configuration?

I am currently working on a web application using React, TypeScript and Webpack. I want Webpack to generate images URLs according to a subdomain that I only know on runtime and not during the compile time.
I've read this on Webpacks's documentation:
http://webpack.github.io/docs/configuration.html#output-publicpath
Note: In cases when the eventual publicPath of of output files isn’t known at compile time, it can be left blank and set dynamically at runtime in the entry point file. If you don’t know the publicPath while compiling you can omit it and set webpack_public_path on your entry point.
webpack_public_path = myRuntimePublicPath
// rest of your application entry
But I can't get it working.
I've set the webpack_public_path variable in my app entry point. But how can I use its value in my Webpack config?
I need to use it here:
"module": {
"rules": [
{
"test": /.(png|jpg|gif)(\?[\s\S]+)?$/,
"loaders": [url?limit=8192&name=/images/[hash].[ext]]
}
]
}
I need to do something like this:
"loaders": ['url?limit=8192&name=__webpack_public_path__/images/[hash].[ext]']
ANSWER
I've managed to make it work. So in my entry point file (start.tsx), I declare de __webpack_public_path__ free var before the imports and I assign its value after the imports.
/// <reference path="./definitions/definitions.d.ts" />
declare let __webpack_public_path__;
import './styles/main.scss';
/* tslint:disable:no-unused-variable */
import * as React from 'react';
/* tslint:enable:no-unused-variable */
import * as ReactDOM from 'react-dom';
import * as Redux from 'redux';
import { Root } from './components/root';
__webpack_public_path__ = `/xxxx/dist/`;
Now, the public path is being used when I have an img tag:
<img src={require('../../images/logo.png')} />
Turns into:
<img src='/xxxx/dist/images/125665qsd64134fqsf.png')} />
Here's my basic setup in terms of the generated HTML:
<script>
window.resourceBaseUrl = 'server-generated-path';
</script>
<script src="path-to-bundle" charset="utf-8"></script>
My main entry point script:
__webpack_public_path__ = window.resourceBaseUrl;
In my case, it was the order I was loading my scripts in my index.html. Ensure the last <script> tag in your index.html has a src attribute.
I discovered this by reading through the generated webpack code:
var scriptUrl;
if (__webpack_require__.g.importScripts) scriptUrl = __webpack_require__.g.location + "";
var document = __webpack_require__.g.document;
if (!scriptUrl && document) {
if (document.currentScript)
scriptUrl = document.currentScript.src
if (!scriptUrl) {
var scripts = document.getElementsByTagName("script");
if(scripts.length) scriptUrl = scripts[scripts.length - 1].src
}
}
// When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration
// or pass an empty string ("") and set the __webpack_public_path__ variable from your code to use your own logic.
if (!scriptUrl) throw new Error("Automatic publicPath is not supported in this browser");
scriptUrl = scriptUrl.replace(/#.*$/, "").replace(/\?.*$/, "").replace(/\/[^\/]+$/, "/");
__webpack_require__.p = scriptUrl;
It just looks through your scripts and picks the last one to set as the scriptUrl which it then uses to figure out if you are using a "publicPath" or not. Since my last script did not have a src attribute, all changes to __webpack_public_path__ or webpack.config.js { ..., output: { publicPath: "" }} were being ignored.
My original index.html:
<body>
<div id="root">
${html}
</div>
<script src="/static/runtime.js" type="module"></script>
<script src="/static/polyfills.js" type="module"></script>
<script src="/static/vendor.js" type="module"></script>
<!-- the below is the offending script -->
<script>
// WARNING: See the following for security issues around embedding JSON in HTML:
// https://redux.js.org/usage/server-rendering#security-considerations
window.__PRELOADED_STATE__ = ${JSON.stringify(preloadedState).replace(
/</g,
'\\u003c'
)}
</script>
</body>
My index.html after my changes:
<body>
<div id="root">
${html}
</div>
<script>
// WARNING: See the following for security issues around embedding JSON in HTML:
// https://redux.js.org/usage/server-rendering#security-considerations
window.__PRELOADED_STATE__ = ${JSON.stringify(preloadedState).replace(
/</g,
'\\u003c'
)}
</script>
<script src="/static/runtime.js" type="module"></script>
<script src="/static/polyfills.js" type="module"></script>
<script src="/static/vendor.js" type="module"></script>
</body>
This took me several days to fix.
Not a big webpack expert, but I'm not sure you are using that loader in the right way. The url-loader is there to help you load files data that are required/imported in your code.
So if in your entry point you write something like:
var imageData = require("path/to/my/file/file.png");
Webpack will see that you are trying to import something different than a .js file and then will search in your configured loader list, to see if it can use any loader to load that resource.
Since you had set up a loader whith a test property that matches your required resource type (extension .png), it will use that configured loader (url-loader) to try loading that resource into your bundle.
You can also tell webpack what loader he needs to use by prepending the loader (and some query strings if you wish) in the require path:
var imageData = require("url-loader?mimetype=image/png!path/to/my/file/file.png");
Also, I'm not sure there is even a name parameter you can pass to the url-loader.

How to use meta tags with dynamic value in react js?

Can anyone help me regarding how to use meta tags with dynamic value in react js?
Please see the image for my requirement,
I am using the extra metatag html tag here(because react require wrap complete html inside the single tag else it raise error). I can also use div/p any html tag, but is this right way to render the react component? having extra html tag than inside that meta tags. Will this work for SEO?
Please suggested me any other good way to use meta tags manually.
I can see few issues regarding the code which you shared.
Meta tags come under head, but your react components would be rendered in your body tag.
Considering SEO part, google can parse JS now so your tags would be read but bing and if you consider yahoo still cannot still do that( Google also is really not that efficient still, faced too many issues regarding while handling SEO's with single page app)
If your reacts components uses Link to navigate to other components which I am assuming it would it case of SPA it would not work, because crawlers try to reach you page directly.
Now,if you have a single page app with a single component you can try react-helmet , but if it involves multiple components and navigations I would suggest you to go for pre-rendering,maybe using phatom-js or pre-render.io(which indirectly uses phantomjs).
If your only concern is meta tags, then you can embed you meta tags directly into your html code and not in the components. This would really help the crawlers to see the meta tags.
But,if you also want crawlers to see your content, pre-rendering is best solution which I can think of now.
If you are serving your React bundle from a server, you can dynamically generate meta tags on the server.
Essentially, in your public/index.html file you want to replace the metadata with an identifiable string:
<!-- in public/index.html -->
<title>$OG_TITLE</title>
<meta name="description" content="$OG_DESCRIPTION" />
<meta property="og:title" content="$OG_TITLE" />
<meta property="og:description" content="$OG_DESCRIPTION" />
<meta property="og:image" content="$OG_IMAGE" />
And then on the server, you want to replace these strings with the dynamically generated information. Here is an example route with Node and Express:
app.get('/about', function(request, response) {
console.log('About page visited!');
const filePath = path.resolve(__dirname, './build', 'index.html')
fs.readFile(filePath, 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
data = data.replace(/\$OG_TITLE/g, 'About Page');
data = data.replace(/\$OG_DESCRIPTION/g, "About page description");
result = data.replace(/\$OG_IMAGE/g, 'https://i.imgur.com/V7irMl8.png');
response.send(result);
});
});
Taken from this tutorial here: https://www.kapwing.com/blog/how-to-add-dynamic-meta-tags-server-side-with-create-react-app/
Create React App produces a static bundle with HTML, JS, and CSS. It can’t possibly give you a dynamic <meta> tag because the result HTML is created ahead of time.
While changing document.title with something like React Helmet makes sense, changing <meta> tags doesn’t make sense unless your app is server rendered. Server rendering is not a supported feature of Create React App so if you want to use it, you might want to check out some alternatives such as Next.js.
That said, if you don’t want full server rendering and only need to change <meta> tags, you could do this by hand as described here.
I hope this helps!
** no need to install express node and all..
** just add react-helmat & must add Helmat-meta tag all routing container. (otherwise its still show home page meta tag)
** react return single element, so you must add into parent element like (div, form)
import { Helmet } from "react-helmet";
import MetaDataJSON from "./MetaDataJSON_File";
constructor(){
this.metaDetails = {};
}
UNSAFE_componentWillMount(){
let curPath = window.location.pathname
this.metaDetails = getMetaData(curPath);
}
export const getMetaData = (pathname) =>{
const metaObj = MetaDataJSON; // import meta json and check the route path is in equal to your meta json file
let metaPath = Object.keys(metaObj);
if (metaPath.indexOf(pathname) >= 0) {
return metaObj[pathname];
}else{
return metaObj["/"];
}
}
// you must add in all component (where routing container)
render(){
return(
<div>
<Helmet>
<title>{this.metaDetails.title}</title>
<meta name="description" content= {this.metaDetails.description}/>
<meta name="keywords" content= {this.metaDetails.keywords} />
</Helmet>
<div>
)
}
There Is a Package Named React-Helmet available it helps to take control over Your Head tags on each route.
Helmet takes plain HTML tags and outputs plain HTML tags. It’s dead simple, and React beginner friendly.
<Helmet>
<title>{context.StoreName}</title>
<meta name="theme-color" content={`${context.ThemeColor}`}/>
</Helmet>
reference - https://codeburst.io/how-to-control-head-tags-in-react-seo-friendly-8264e1194880

Resources