Skip to content

Commit 7c224b6

Browse files
Navigation
1 parent 07ce878 commit 7c224b6

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

react.js

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1415,4 +1415,66 @@ const FunctionalComponent = () => {
14151415
</Switch>
14161416
</Router>
14171417
);
1418+
};
1419+
1420+
1421+
1422+
// Link and NavLink
1423+
import { Link, NavLink } from 'react-router-dom';
1424+
const FunctionalComponent = () => {
1425+
return (
1426+
<nav>
1427+
<NavLink to="/" style={isActive => ({color: isActive ? 'red' : ''})}>Home</NavLink>
1428+
<Link to="/">Blog</Link>
1429+
</nav>
1430+
)
1431+
};
1432+
1433+
// navigate
1434+
import ( useNavigate ) from 'react-router-dom';
1435+
const navigate = useNavigate();
1436+
const FunctionalComponent = () => {
1437+
return (
1438+
<>
1439+
<button onClick={() => navigate('/')}>Go Root</button>
1440+
{/* navigate and pass data */}
1441+
<button onClick={() => navigate('/', {data: {title: 'test'}})}>Go Root with title data</button>
1442+
</>
1443+
)
1444+
};
1445+
1446+
// history !stop using in V6! -> useNavigate
1447+
import ( useHistory ) from 'react-router-dom';
1448+
const FunctionalComponent = () => {
1449+
const history = useHistory();
1450+
return (
1451+
<>
1452+
<button onClick={history.push('/')}>Go Root</button>
1453+
<button onClick={history.goBack()}>Go Back</button>
1454+
<button onClick={history.goForward()}>Go Forward</button>
1455+
<button onClick={history.go(-2)}>Go Back 2</button>
1456+
</>
1457+
)
1458+
};
1459+
1460+
// location; you can check current path or query params
1461+
import { useLocation } from 'react-router-dom';
1462+
const { pathname, search } = useLocation();
1463+
const queryParams = new URLSearchParams(search);
1464+
const FunctionalComponent = () => {
1465+
return (
1466+
<>
1467+
{/* assuming we are on /blog?sort=inverted */}
1468+
<p>Pathname: {pathname}</p>
1469+
{pathname === 'blog' && <p>You are on blog page</p>} {/* conditional based on path */}
1470+
<p>Query params: {queryParams.get('sort')}</p>
1471+
</>
1472+
)
1473+
};
1474+
1475+
// params from the navigation
1476+
import ( useParams ) from 'react-router-dom';
1477+
const { blogPost } = useParams(); // assuming we are in a <Route>: /blog/:blogPost
1478+
const FunctionalComponent = () => {
1479+
return <p>{blogPost}</p> // /blog/test will render 'test'
14181480
};

0 commit comments

Comments
 (0)