Passing data from server to the React App

This article shows how to pass json data from Express.js or AEM backend to the React app

Image for post
Image for post

Client

npx create-react-app client
// client/AppContext.jsimport React, { createContext, useState } from 'react';const AppContext = createContext();
const user = window.__user || { displayName: 'Anonymous' };const INIT_STATE = { user };const AppContextProvider = ({ children }) => { const [app, setApp] = useState(INIT_STATE); return (
<AppContext.Provider value={{ app, setApp }}>
{children}
</AppContext.Provider>
);
};
const AppContextConsumer = AppContext.Consumer;export { AppContext, AppContextProvider, AppContextConsumer };
export default AppContext;
// client/App.jsimport './App.css';import { AppContextProvider } from './AppContext'import View from './View';
function App() { return ( <AppContextProvider> <View /> </AppContextProvider> );}export default App;
// client/View.jsimport React, { useContext } from 'react';import AppContext from './AppContext';
const View = ({ children }) => { const { app } = useContext(AppContext); const { user } = app; return ( <div> Hello, { user.displayName }!</div> );};export default View;

Server

Express.js

express --view=ejs server
<!-- views/index.ejs --><!doctype html><html lang="en"><head>   <script type="text/javascript">      window.__user = JSON.parse(`<%- JSON.stringify(user); %>`);   </script></head><%- include('../../client/build/client.html')%></html>
// server/app.jsapp.engine('html', require('ejs').renderFile);...app.use(express.static(path.join(__dirname, '../client/build/')))
// server/routes/index.jsrouter.get('/', function(req, res, next) {   res.render('index', { user: { displayName: 'John Smith' } });});
// client/package.json"postbuild": "mv build/index.html build/client.html"

AEM

mvn -B archetype:generate \
-D archetypeGroupId=com.adobe.aem \
-D archetypeArtifactId=aem-project-archetype \
-D archetypeVersion=24 \
-D appTitle="My Site" \
-D appId="mysite" \
-D groupId="com.mysite" \
-D frontendModule="react"
// /apps/mysite/components/page/user.js'use strict'

use(function() {

return {
displayName: 'John Smith'
}
})
<!-- /apps/mysite/components/page/customheaderlibs.html -->
<sly data-sly-use.user="user.js"></sly>
<script>
window.__user = {
displayName: '${user.displayName @ context="scriptString"}'
};
</script>

Conclusions

References

Technical Architect @ Adobe

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store