Reputation: 5599
I'm building an react app with an express backend. I'm now adding socket io chat functionality to the front end. Everything works as expected but now I want to access params from the url to set the socket-io channel name.
I want the user to visit localhost:3000/foo
and the react frontend to be able to access the foo
parameter.
What's the best way to do this?
At the moment I am serving the static files like so:
app.use(express.static(`${__dirname}/../client/dist`));
I tried to add react-router-dom with the following code but it doesnt display the page at all:
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route } from 'react-router-dom'
import App from './components/App.jsx';
ReactDOM.render(
<Router>
<Route path="/:id" component={App} />
</Router>,
document.querySelector('#app'));
Whenever I add something to the end of the url (I fi type in something other than ‘/‘ the page does not display. I get the error “cannot GET /foo”
I've also tried this but then the front end doesn't display either:
app.get('/:id', (req, res) => {
console.log('-----------', req.params.id)
})
My ultimate goal would be to only display the chat app when a user visits localhost:3000/chat/:channelId
Upvotes: 0
Views: 2893
Reputation: 3362
By referring the answer provided by @mavarazy. You could write it in a class and get the parameter via props.
export default class User extends Component {
constructor(props) {
super(props)
}
render() {
return (
<div>
<h2>You are listening to: {this.props.match.params.id}</h2>
</div>
)
}
Upvotes: 0
Reputation: 7735
If you are using react-router
your approach is perfectly fine, you should be able to retrieve channel name from match
parameter
const App = ({ match }) => (
<div>
<h2>You are listening to: {match.params.id}</h2>
</div>
)
Look at https://reacttraining.com/react-router/web/example/ambiguous-matches
Upvotes: 1