'Pass parameter from non-react jquery html form page to react app
I am new to reactJS. I have a simple react app that runs fine independently.
Now I am calling it from exising HTML page and want to pass a parameter to react app and use that parameter inside react app.
I googled and found that window environment variable can be set and can be picked in the react app.
How do I do that? Any thoughts or samples, please?
Thanks!
Here is my scenario,
<html>
...
<body>
...
<a href="http://server.com/reactapp/index.html">call react app</a>
<input type="hidden" id="empno" value="1000" />
....
</body>
</html>
----
React app
index.js
--------------
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
let eno = document.getElementById("empno");
ReactDOM.render(<Products empnumber={eno}/>, document.getElementById('root'));
app.js
------
...
render() {
console.log(this.props.empnumber);
console log displays null. Thanks!
Solution 1:[1]
You may find this article useful:
The way our React component receives data from the outside world is via its props. Whenever we need to update the component with new data — and this is the part that feels magic in its simplicity — we just render it again using the new props, and React knows how to do it efficiently.
In a nutshell, find the part that calls ReactDOM.render(<App/>, container) or similar, and pass your value as a property to App, such as <App someprop={somevalue}/>
Solution 2:[2]
You can pass values to your React component when you're mounting it to the dom like so:
const someJson = {
value1: '123',
value2: '456',
};
render(<App someProp={someJson} />, document.getElementById('root'));
Solution 3:[3]
If you are accessing your react app via a link as you described you could use query strings?
<a href="http://server.com/reactapp/index.html?empnumber=1234">call react app</a>
then in your component you can access the query string like this
render() {
console.log(this.props.location.query.empnumber);
}
there is also a nice npm library to access query string from React component
Solution 4:[4]
const querystring=window.location.search;
const urlParams=new URLSearchParams(querystring);
const empnumber=urlParams.get('empnumber');
You can then pass the variables as props to your component
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dan Burzo |
| Solution 2 | Anas |
| Solution 3 | stackoverfloweth |
| Solution 4 | user3280322 |
