0

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

grabury
  • 4,667
  • 9
  • 48
  • 92
  • Why does the Route approach does not work? You should be able to access params in `App` from match parameter – mavarazy Jan 29 '18 at 08:09
  • 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” – grabury Jan 29 '18 at 08:38

2 Answers2

1

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

mavarazy
  • 7,208
  • 1
  • 30
  • 56
0

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>
   )
  }
Hunter
  • 1,834
  • 15
  • 20