Basic
Is it possible to have multiple “#” in a url?
http://www.example.com/hey#foo#bar
which is the same window.location.hash for
http://www.example.com/hey#foo%23bar
How to use “react-router”?
How to create a browser router?
import { BrowserRouter, Route, Switch, Redirect } from 'react-router-dom' const redirectTest = 'users/1' // http://localhost/users/1 const App = () => { return ( <> {/* Load page with new path but keeping Header */} <Header /> {/* CREATE A BROWSER ROUTER */} <BrowserRouter> <Switch> {/* Redirect from root path to a different path */} <Redirect exact from='/' to={`/${redirectTest}`} /> {/* Render specific component basing on url param} <Route path='users/:id/' component={renderComponent} /> {/* ... */} {/* Render 404 page if url doesn't match any format} <Route component={render404} /> </Switch> </BrowserRouter> {/* Load page with new path but keeping Footer */} <Footer /> </> ) } function renderComponent(props: any) { const { id } = props.match.params return ( <UserDetail userId={id} /> ) } function render404(): any { window.location.href = 'https://www.myhomepage.com/404#/' return null } export default App
How to pass data to child component?
// Add param inside component <Route exact path="/details/:id" component={DetailsPage} />
// Access param inside component props.match.params.id
or
<Route exact path="/details/:id" render={(props) => ( <DetailsPage id={props.match.params.id}/> )} />
How to access router params anywhere in child components?
import { useParams } from "react-router-dom"; const EditPost = () => { const params = useParams(); return <p>Your Post ID is: {params.id}</p> } export default EditPost;
How to configure url for tabs?
import { Tab, TabList } from 'react-tabs' import { Link } from 'react-router-dom' const TabHeader = ({ tabList }) => { return ( <TabList> {tabList.map((element) => { <Tab> {/* Tab "users": http://localhost#/users */} {/* Tab "products": http://localhost#/products */} <Link to={`#/${element.url}`}> {element.tabTitle} </Link> </Tab> ) })} </TabList> ) } export default TabHeader
Others
How to add clickable to the site?
function Navbar() { return ( <div> <Link to="/">Home</Link> <Link to="/about">About Us</Link> <Link to="/shop">Shop Now</Link> <Link to={{ pathname: '/profile', state: {infoId: info.id}, }} >Profile</Link> </div> ); };
// Access state from props.location.state
How to update the url without causing a navigation/reload?
When you declare Route path
// input 2021-08-06/melbourne/race/7/results#/... <Route path='/:date/:location/' component={renderComponent} />
And you want to update number “7” to “6”
const history = useHistory() history.push("6") // output: 2021-08-06/melbourne/race/6/
Leave a Reply