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

2
  • Why does the Route approach does not work? You should be able to access params in App from match parameter Commented Jan 29, 2018 at 8: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” Commented Jan 29, 2018 at 8:38

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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>
   )
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.