reactJS application on Amazon Web Services with passed in values - reactjs

I have a reactJS application which is currently hosted in an S3 bucket on Amazon Web Services. Amazon has provided me with an entry point to my application, lets assume the entry point is
http://myreactjsapp.s3-website.us-east-2.amazonaws.com/
What I would like to do is be able to pass a value into the application and have that value available within the app. So, for example, I would like to do something like this:
http://401kmobileapp.s3-website.us-east-2.amazonaws.com/?userFirstName=Jonathan&userLastName=Small
Then, I would like to be able to reference the value of userFirstName and the value of userLastName within the app so when I display my default page, the application can display something like Welcome Jonathan Small!
How would I do this?
Thank you for any suggestions.

You can use the URLSearchParams API to parse the query parameters and put them in your component state and use it for rendering.
Example
class App extends React.Component {
constructor(props) {
super(props);
const urlParams = new URLSearchParams(window.location.search);
this.state = {
userFirstName: urlParams.get("userFirstName") || "",
userLastName: urlParams.get("userLastName") || ""
};
}
render() {
const { userFirstName, userLastName } = this.state;
return (
<div>
Welcome {userFirstName} {userLastName}
</div>
);
}
}

Related

how to implement react-redux in micro frontend architecture with individual MFE?

might be question is duplicated ,even though my business case is little bit different since I need help from experts.
First time, I am using Micro frontend architecture in current project with help of single spa framework
with reactjs.
I have experience in reactjs with redux(thunk,saga) but in single spa, I am unable to intercept the provider with store in individual MFE root component.
anybody has used reactjs with Single SPA framework along with redux with individual MFE.
my all MFE are in reactjs only.
#reactjs #redux #redux-saga.
I have implemented in some time back, was using redux for inter app communication between MFEs as well.
Store was build separately in child app.
This store would be imported by the master app and registered in global event distributor in the master app.
class GlobalEventDistributor {
constructor() {
this.stores = [];
}
registerStore(store) {
this.stores.push(store);
}
dispatch(event) {
this.stores.forEach((s) => s.dispatch(event));
}
}
This GlobalEventDistributor along with the store will be passed as a custom prop while registering application.
let storeModule = {},
customProps = {
globalEventDistributor: globalEventDistributor,
...additionalProps,
};
try {
storeModule = storeURL
? await SystemJS.import(storeURL)
: { storeInstance: null };
} catch (e) {
console.error(`Could not load store of app ${name}.`, e);
}
if (storeModule.storeInstance && globalEventDistributor) {
// add a reference of the store to the customProps
customProps.store = storeModule.storeInstance;
// register the store with the globalEventDistributor
globalEventDistributor.registerStore(storeModule.storeInstance);
}
// register the app with singleSPA and pass a reference to the store of the app as well as a reference to the globalEventDistributor
singleSpa.registerApplication(
name,
() => SystemJS.import(appURL),
hashPrefix(hash, wild),
customProps
);
After passing as customer props store and GlobalEventDispatcher will be available in the rootComponent passed to singleSpaReact of child app. From rootComponent it will be passed as a prop to Provider
I have referred below repo while implementing it.
https://github.com/me-12/single-spa-portal-example
Note: Currently we have are migrating to Module Federation instead of using singleSPA you can try that too.

Symfony4 backend with frontend react. best and safest way to pass information?

I am learning React and want to create an application with Symfony4 as my backend and React frontend. I am stuck now when I need to pass some kind of data to the frontend from my backend. I don't really know what is the right way to do it? Following some tutorials I am doing it like this:
From the controller I send some data to the twig file:
/**
* #Route("/")
*/
public function homepage()
{
$date = new DateTime();
$curr_date = $date->format('Y-m-d H:i:s');
return $this->render('base.html.twig', [
'gameDate' => $curr_date
]);
}
In the twig file, I set it as a data-attribute
base.html.twig:
<div id="root" data-event-date="{{ gameDate }}">
Then I can get the variable as a dataset in my JavaScript
App.js:
const root = document.getElementById('root');
ReactDOM.render(<Homepage {...(root.dataset)}/>, root);
And render it from props.
Homepage.js:
class Homepage extends Component {
constructor(props) {
super(props)
this.state = {
prizePool: '',
gameDate: '',
numberOfPlayers: ''
}
}
onParticipateClick = (event) => {
this.setState({prizePool: Math.random()})
}
render()
{
return (
<div className="mt-c-10">
<GameInfoBox gameDate={this.props.eventDate}/>
</div>
)
}
}
This actually works, but I am concerned with showing all the information in data variables because anyone can see it. What if I want to pass user ID or something secret? There should be another way to do it right?
It depend on what you attemps, if you are working on big project, you can use API to serve backend data. Take a look here: https://www.modernjsforphpdevs.com/react-symfony-4-starter-repo/. There is a simple example.
But if you want something more use api-platform or FOSRestBundle.
"Best and safest" is a little ambiguous - do you need strict security, or safe as in code stability etc?
Instead of passing your data from controller to view (twig) and then into HTML elements or global, another way is this:
Controller loads the view file with your nav and other stuff
Controller loads React (however you do this, Webpack etc)
React calls another controller (i.e. fetch()). This controller is probably somewhere like src/Api/Controller/ as it wont render a view so keep it separate to the other controllers which do render a view
The API controller calls your DB or remote API (etc) and gets the data and sends it back as JsonResponse back to React.
React can then show the data, or an error message depending on the response status
The API controller in your MW can also handle errors and do some logging, so React just gets a 200 and the data or a 400 (or whatever) and it can show a nice message to the user as normal.

How to delay component rendering when response from the server is delayed

I am a newbie to react. I have a situation where in I am fetching some data from the server which I want to display in a page. I am using websockets for communication between the client and server. As the server makes a request to some third party API the response gets delayed. But my component gets rendered before the response comes. I have seen answers which talks about handling such situation in case of ajax request. But how do i handle it in the case of web sockets. My sample jsx page which I want to render after getting response from server is as follows
import React ,{PureComponent} from 'react';
export default class ScorePanel extends PureComponent{
constructor(props){
super(props);
var d = new Date();
this.currentDate = d.getFullYear()+"-"+d.getMonth()+ "-"+ d.getDate();
this.week ="1";
this.numQuarters =1;
}
getInitialState(){
return {
resultsObtianed: false
}
}
getScores(){
return this.props.scores ||[];
}
render() {
return <div className = 'scorePanel'>
if ( !this.state.response ) {
return <div>loging response</div>
}
{
// data to render after geting response from server
}
}
How do I let the client know that response from the server has been received and it's time to render a component. It would be better if I can show a loading page if the response gets delayed. So I would like to make use of getInitialState function as well. I am dispatching an action to the server on a button click in the navigation bar. Thanks for the help in advance
Assuming you have a websocket ws, and listening to "test" event.
in your oncomponentDidMount do
componentDidMount()
{
ws.on("test",(data)=>{
this.setState({response:data})
})
}
also I like to predefine state, so I'd add this.state={response:{}} in constructor

Can't connect react.js login to SpringBoot app

I am trying to call REST endpoints on one application (spring-boot) from another (reactjs). The applications are running on the following hosts and ports.
REST application, using spring boot, http://localhost:8080
HTML application, using reactjs, http://localhost:9000
I am trying to send the login info from reactjs to spring-boot but without success.
Reactjs:
import React from 'react';
export default class Login extends React.Component {
constructor() {
super();
this.state = {
login:"",
password:""
};
this.handleChange = this.handleChange.bind(this);
}
handleChange() {
this.setState({login: this.state.login});
}
render() {
return (
<form role="form">
<div>
<input type="text" name="login" onChange={this.handleChange} />
<input type="password" name="password"/>
</div>
<button onClick={this.login.bind(this)}>Login</button>
</form>
);
}
login () {
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
var url = "http://localhost:8080/test/login"
xmlhttp.open("POST", url );
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({login: this.state.login}));
}
}
and Spring-boot:
#CrossOrigin(origins = "http://localhost:9000")
#RequestMapping(value = "/test/login")
public Boolean testLogin(#RequestParam String login) {
if ( login.equals ("ajt"))
return true;
else {
return false;
}
}
I can see that the two apps are connecting for even though reactjs gives me error 400, when I submit, the console of the Spring-boot app tells me:
Resolved exception caused by Handler execution: org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'login' is not present
I can only assume that from the Spring-boot side, it cannot translate what ever is sent via react.js.
ps: bear with me, I have been coding for about 6 months.
I knew this looked familiar. Sorry my last answer didn't fix all your issues.
Your current problem is here;
public Boolean testLogin(#RequestParam String login) {
Should be
public Boolean testLogin(#RequestBody String login) {
EDIT:: Second problem.
Your handleChange function isn't taking in any values! It should look more like this;
handleChange(value) {
this.setState({login: value});
}
When your input field calls this function, it needs to pass a value from the input into the state. Your current code is essentially the same as this;
this.state.login = this.state.login;
Which obviously isn't going to get you anywhere.
Try that change. If it still does not work, be sure you open your dev-tools in your browser and step through the code line by line to be sure it is executing and storing the values you want it to.

Display logged in user's first name onto page (from database)

In preparing a welcome page after a user has logged in, I'd like the page title to display their first name which is found in the user ID database (e.g - "Welcome, Sally!"). This is a bit different than just using a cookie to relay the username in a location; like for example in the top corner to access user settings.
The site is being built with React, if that affects the code needed.
Any suggestions?
are you asking how to get the username in the app state? or just how you would render that?
if you already have the firstname in an auth object in state you could do something like this:
class WelcomePage extends Component {
render() {
const { auth } = this.props
var pageTitle = `Welcome, { auth.firstname }`
return (
<h1>{ pageTitle }</h1>
)
}
}
export default WelcomePage
otherwise I would need more information to understand what you're asking
Here is a solution I worked out that seems to do the job. This lies within the React component for the page rendering.
render: function(){
var user = JSON.parse(localStorage.getItem('user'));
...
return (
<div>
<h2>Welcome, {user.firstname1}!</h2>
</div>
Here's a quick screen shot of the result ("Candy" being the logged-in user's first name):

Resources