Alwaysblue
Alwaysblue

Reputation: 11830

Creating dynamic Link with some text before it

I was building a search engine for custom project.

There I have a search bar from where user can search.

When the user searches, I want the given link to work as it works in case of google

www.google.com/ search? queryRelatedInfo

Notice the search? and then whatever query/parameter/ID

for this I tried something like this in

import React, {Component} from 'react';
import { 
  BrowserRouter, 
  Route, 
  Switch,
  Redirect,
} from 'react-router-dom';
import SearchScreen from "./container/searchScreen.js"
import HomeScreen from "./container/home.js";


class route extends Component {
    render () {
        return (
            <BrowserRouter>
                <div>
                    <Switch>
                        <Route path ="/" exact render ={(props) => <HomeScreen {...props}/>} />
                        <Route path ="/search?:id"  exact render ={(props) => <SearchScreen {...props}/>} />
                    </Switch>
                </div>
            </BrowserRouter>
        )
    }
}

export default route

Notice, <Route path ="/search?:id" above.

Unfortunately this didn't worked out.

I understand that <Route path ="/:id" works but how can i make <Route path ="/search?:id to work i.e how can I make some link like http://localhost:3000/search?9e9e to work

Upvotes: 1

Views: 130

Answers (2)

Mohamed Binothman
Mohamed Binothman

Reputation: 378

you don't need to put the path like this /search?:id, just put it search

<Route path ="/search"  exact render ={(props) => <SearchScreen {...props}/>} />

then inside your SearchScreen component, get the value of search parameter from the URL, check this issue will help.

after the user make search, pass the value like this /search?s=value_here

Upvotes: 0

sdkcy
sdkcy

Reputation: 3548

I think this is related with historyApiFallback. That parameter; (https://webpack.js.org/configuration/dev-server/#devserver-historyapifallback)

When using the HTML5 History API, the index.html page will likely have to be served in place of any 404 responses. devServer.historyApiFallback is disabled by default. Enable it by passing:

module.exports = {
  //...
  devServer: {
    historyApiFallback: true
  }
};

Your react app is a single page application. So all path except home path actually is an virtual path, they are not physically exist. The paths must routed to home path. So react-router can manage.

Upvotes: 1

Related Questions