I'm building a game using Express and React. I need to access the userId in my index.jsx file to perform actions on my controllers, like increment the user score.
My route renders an index.pug file while passing a user_id param:
//server.js
app.get('/', function (req, res) {
const userId = req.query.userId
res.render('index', {userId: userId})
})
Then I can access the userId in my pug file, like this:
// index.pug
body
div#errors
#root
p #{userId} // prints the User Id
Now I need to access this userId param in my index.jsx file that contains the React Components.
class Cell extends React.Component {
render() {
return (
<button onClick={() => this.props.onClick()}>
{userId}
</button>
)
}
}
But that doesn't work, as I expected. Any ideas?
You can do using window object
Let's say in your .pug file
script.
var userId = '#{userId}'; //assigning pug value to window object.
Now you can access userId in react component as window.userId
class Cell extends React.Component {
render() {
return (
<button onClick={() => this.props.onClick()}>
{window.userId}
</button>
)
}
}