score:1

You could check to see if this.props.match.username exists. If it does then render as normal if it doesnt then use React-Router Redirect Component to redirect to a 404 component. If you have multiple paths that require this functionality then you may consider making a HOC for this purpose.

score:2

Use Switch then Redirect

https://reacttraining.com/react-router/web/example/no-match

https://reacttraining.com/react-router/web/api/Redirect

Valid URL no redirect: /user/valid_username

404 URL redirects: /user/invalid_username

import React, { Component } from 'react'
import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom'

class App extends Component {
  render() {
    return (
      <Router>
        <div>
          <Switch>
            <Route path="/user/:username" component={Child} />
            <Route path="/404" component={NoMatch} />
            <Route component={NoMatch} />
          </Switch>
        </div>
      </Router>
    )
  }
}

function Child({ match }) {
  // perform some username check
  if (match.params.username !== 'valid_username') {
    return (
      <div>
        <Redirect to="/404" />
      </div>
    )
  }
  return (
    <div className="App">
      <h3>ID: {match.params.username}</h3>
    </div>
  )
}

function NoMatch({ location }) {
  return (
    <div>
      <h3>
        404 - No match for <code>{location.pathname}</code>
      </h3>
    </div>
  )
}

export default App

Related Query

More Query from same tag