0

Based on official how to:

Add React to Website at https://reactjs.org/docs/add-react-to-a-website.html

I created test.html with content:

<!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>

    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

    <!-- Load our React component. -->
    <script src="test.js"></script>

  </body>
</html>

And test.js:

'use strict';

const e = React.createElement;

class LikeButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = { liked: false };
  }

  componentDidMount() {
    axios.get(`http://localhost:4000/api/v1/cars`)
      .then(result => {
        console.log(result.data[0].make);
      })
  }

  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);

The code above is working well.

I'm able to press Like button and see the change, also able to use libraries such as Axios.

Now I want to open http://localhost/test.html?param1=111&param2=222 and get these param1 and param2 variables inside test.js - React. Is that possible? How to achieve this?

Many thanks

laimison
  • 1,409
  • 3
  • 17
  • 39
  • 3
    Why should react change the way you access query parameters? https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript – Olian04 Aug 07 '19 at 23:42

1 Answers1

1

Just as you perform a fetch in ComponentDidMount, you can check query params in the same lifecycle event. Building on the link shared by @Olian04, here's how that'd look:

  componentDidMount() {
    const urlParams = new URLSearchParams(window.location.search);

    if (urlParams.has("param1")) {
      console.log(urlParams.get("param1"));
    } else {
      console.log("param1 was not found");
    }

    if (urlParams.has("param2")) {
      console.log(urlParams.get("param2"));
    } else {
      console.log("param2 was not found");
    }
  }
It'sNotMe
  • 1,184
  • 1
  • 9
  • 29