devAR
devAR

Reputation: 458

Send user to a link from search bar query

I have a searchbar, after a user clicks enter, it takes them to a link with whatever is in the search bar.

In my app.js I have this route

<Route path='/web/:something' component={() => 
   <SearchResults />
}/>

Then I have a search component

|const Search = () => {

    const [query, setquery] = useState(null)

    const onClick2= () => {
        var x = document.getElementById("navBarSearchForm").value;
        if(x) {
          setquery(x)
        }
    }
    console.log(query)
    
    return (
        <div className="search">
            <div className="input-group">
                <input type="search" id="navBarSearchForm" className="form-control rounded" placeholder="Enter Website URL To Get Analytics" aria-label="Search"
                 aria-describedby="search-addon"></input>
                 <button onClick={onClick2} type="button" id="searchbutton" className="btn btn-outline-primary"><Link to={`/web/${query}`}>search</Link></button>
            </div>
        </div>
    )
}

export default Search

The issue with this is that regardless of what ever the user enters in the searchbar it takes them to null, example localhost:3000/web/null, which is probably because it sends the user to the link before the state has time to change?

To try to solve this issue I wrapped the search button in a ternary operator like so:

        <div className="search">
            <div className="input-group">
                <input type="search" id="navBarSearchForm" className="form-control rounded" placeholder="Enter Website URL To Get Analytics" aria-label="Search"
                 aria-describedby="search-addon"></input>
                 {website ?
                  (<button onClick={onClick2} type="button" id="searchbutton" className="btn btn-outline-primary"><Link to={`/web/${query}`}>search</Link></button>)
                :
                  (<button onClick={onClick2} type="button" id="searchbutton" className="btn btn-outline-primary"><Link to={`/`}>search</Link></button>)}
            </div>
        </div>

Now, this works but the only issue is that the user has to double click the search button, which is'nt ideal. How can I solve this so that it will take them to link with just one click with whatever they enter in the searchbar?

Or is there a better way of doing this?

Upvotes: 0

Views: 451

Answers (1)

DevAddict
DevAddict

Reputation: 2013

you can use useHistory Hook from react-router-dom and then use the push method on history object to go to new route.

import {useHistory} from 'react-router-dom';

const Component = () => {
    const history = useHistory();
    
    ...
    
    const onClick = () => {
        history.push(yourRouteOfChoice);
    };
    
    ...
    
    return (
        <div onClick={onClick}>
            ...
        </div>
    );
};

BTW use some better naming for your functions it will help you in the future.

Upvotes: 1

Related Questions