reactJS application on Amazon Web Services with passed in values

Viewed 24

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.

1 Answers

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