Reputation: 23
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!
Upvotes: 1
Views: 1983
Reputation: 11
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
Upvotes: 1
Reputation: 6917
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
Upvotes: 0
Reputation: 5727
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'));
Upvotes: 1
Reputation: 10060
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}/>
Upvotes: 1