├── public ├── robots.txt ├── favicon.ico ├── logo192.png ├── logo512.png ├── manifest.json └── index.html ├── src ├── setupTests.js ├── index.css ├── App.test.js ├── App.js ├── index.js ├── components │ └── Header │ │ ├── Navbar.js │ │ ├── Welcome.js │ │ ├── Navbar.css │ │ ├── About.js │ │ └── Welcome.css ├── hooks │ └── useSticky.js ├── serviceWorker.js └── assets │ └── images │ └── logo.svg ├── .gitignore ├── README.md ├── package.json └── .vscode └── settings.json /public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ibrahima92/react-sticky-navbar/HEAD/public/favicon.ico -------------------------------------------------------------------------------- /public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ibrahima92/react-sticky-navbar/HEAD/public/logo192.png -------------------------------------------------------------------------------- /public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ibrahima92/react-sticky-navbar/HEAD/public/logo512.png -------------------------------------------------------------------------------- /src/setupTests.js: -------------------------------------------------------------------------------- 1 | // jest-dom adds custom jest matchers for asserting on DOM nodes. 2 | // allows you to do things like: 3 | // expect(element).toHaveTextContent(/react/i) 4 | // learn more: https://github.com/testing-library/jest-dom 5 | import '@testing-library/jest-dom/extend-expect'; 6 | -------------------------------------------------------------------------------- /src/index.css: -------------------------------------------------------------------------------- 1 | @import url("https://fonts.googleapis.com/css?family=Open+Sans:400,700&display=swap"); 2 | 3 | * { 4 | margin: 0; 5 | padding: 0; 6 | box-sizing: border-box; 7 | } 8 | 9 | body { 10 | font-family: "Open Sans", sans-serif; 11 | color: #fff; 12 | font-size: 1rem; 13 | } 14 | -------------------------------------------------------------------------------- /src/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { render } from '@testing-library/react'; 3 | import App from './App'; 4 | 5 | test('renders learn react link', () => { 6 | const { getByText } = render(); 7 | const linkElement = getByText(/learn react/i); 8 | expect(linkElement).toBeInTheDocument(); 9 | }); 10 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /src/App.js: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import useSticky from './hooks/useSticky.js' 3 | import Welcome from './components/Header/Welcome' 4 | import Navbar from './components/Header/Navbar' 5 | 6 | function App() { 7 | const { isSticky, element } = useSticky() 8 | return ( 9 | <> 10 | 11 | 12 | 13 | ) 14 | } 15 | 16 | export default App 17 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './App'; 5 | import * as serviceWorker from './serviceWorker'; 6 | 7 | ReactDOM.render(, document.getElementById('root')); 8 | 9 | // If you want your app to work offline and load faster, you can change 10 | // unregister() to register() below. Note this comes with some pitfalls. 11 | // Learn more about service workers: https://bit.ly/CRA-PWA 12 | serviceWorker.unregister(); 13 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # How to Build a sticky navigation bar with React Hooks 2 | I'm pretty sure that you've already seen the effect we are going to make today - It's a common animation that we see on a lot of websites. When the user scrolls, the navigation bar moves down with a cool animation effect. 3 | 4 | You're lucky today because, in this post, we'll replicate the same effect with React by building a sticky navbar from scratch with a custom hook. 5 | 6 | Find the full article on [my blog](https://www.ibrahima-ndaw.com/blog/build-a-sticky-nav-with-react/) 7 | -------------------------------------------------------------------------------- /public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /src/components/Header/Navbar.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import "./Navbar.css"; 3 | import Logo from "../../assets/images/logo.svg"; 4 | 5 | const Navbar = ({ sticky }) => { 6 | return ( 7 | 19 | )}; 20 | export default Navbar; 21 | -------------------------------------------------------------------------------- /src/components/Header/Welcome.js: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | 3 | import './Welcome.css' 4 | import Logo from '../../assets/images/logo.svg' 5 | import About from './About' 6 | 7 | const Welcome = ({element}) => { 8 | return ( 9 |
10 |
11 |
12 | logo 13 |

Even if you scroll, i will stick with you

14 | 17 |
18 |
19 | 20 | 21 | 22 |
23 | ) 24 | } 25 | 26 | export default Welcome 27 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-sticky-navbar", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@testing-library/jest-dom": "^4.2.4", 7 | "@testing-library/react": "^9.3.2", 8 | "@testing-library/user-event": "^7.1.2", 9 | "react": "^16.12.0", 10 | "react-dom": "^16.12.0", 11 | "react-scripts": "3.3.0" 12 | }, 13 | "scripts": { 14 | "start": "react-scripts start", 15 | "build": "react-scripts build", 16 | "test": "react-scripts test", 17 | "eject": "react-scripts eject" 18 | }, 19 | "eslintConfig": { 20 | "extends": "react-app" 21 | }, 22 | "browserslist": { 23 | "production": [ 24 | ">0.2%", 25 | "not dead", 26 | "not op_mini all" 27 | ], 28 | "development": [ 29 | "last 1 chrome version", 30 | "last 1 firefox version", 31 | "last 1 safari version" 32 | ] 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "workbench.colorCustomizations": { 3 | "activityBar.background": "#1accff", 4 | "activityBar.activeBorder": "#df00ad", 5 | "activityBar.foreground": "#15202b", 6 | "activityBar.inactiveForeground": "#15202b99", 7 | "activityBarBadge.background": "#df00ad", 8 | "activityBarBadge.foreground": "#e7e7e7", 9 | "titleBar.activeBackground": "#00b3e6", 10 | "titleBar.inactiveBackground": "#00b3e699", 11 | "titleBar.activeForeground": "#15202b", 12 | "titleBar.inactiveForeground": "#15202b99", 13 | "statusBar.background": "#00b3e6", 14 | "statusBarItem.hoverBackground": "#008bb3", 15 | "statusBar.foreground": "#15202b", 16 | "activityBar.activeBackground": "#1accff", 17 | "statusBar.border": "#00b3e6", 18 | "titleBar.border": "#00b3e6" 19 | }, 20 | "peacock.color": "#00b3e6" 21 | } -------------------------------------------------------------------------------- /src/components/Header/Navbar.css: -------------------------------------------------------------------------------- 1 | .navbar { 2 | display: flex; 3 | align-items: center; 4 | justify-content: space-between; 5 | padding: 0.5rem 2.5rem; 6 | position: absolute; 7 | z-index: 1; 8 | width: 100%; 9 | } 10 | 11 | .navbar-sticky { 12 | background: #333; 13 | position: fixed; 14 | top: 0; 15 | left: 0; 16 | box-shadow: 1px 1px 1px #222; 17 | animation: moveDown 0.5s ease-in-out; 18 | } 19 | 20 | .navbar--logo-holder { 21 | display: flex; 22 | align-items: center; 23 | justify-content: center; 24 | } 25 | 26 | .navbar--logo { 27 | width: 2rem; 28 | height: 2rem; 29 | margin-right: 0.5rem; 30 | animation: rotate 0.7s ease-in-out 0.5s; 31 | } 32 | 33 | .navbar--link { 34 | display: flex; 35 | list-style: none; 36 | } 37 | 38 | .navbar--link-item { 39 | margin: 0.4rem 1rem 0 0; 40 | padding: 0 0.3rem; 41 | cursor: pointer; 42 | } 43 | 44 | @keyframes moveDown { 45 | from { 46 | transform: translateY(-5rem); 47 | } 48 | to { 49 | transform: translateY(0rem); 50 | } 51 | } 52 | 53 | @keyframes rotate { 54 | 0% { 55 | transform: rotateY(360deg); 56 | } 57 | 100% { 58 | transform: rotateY(0rem); 59 | } 60 | } -------------------------------------------------------------------------------- /src/components/Header/About.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | const About = () => ( 4 |
5 |

6 | Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium 7 | doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo 8 | inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. 9 | Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut 10 | fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem 11 | sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit 12 | amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora 13 | incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad 14 | minima veniam, quis nostrum exercitationem ullam corporis suscipit 15 | laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum 16 | iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae 17 | consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur 18 |

19 |
20 | ); 21 | 22 | export default About; 23 | -------------------------------------------------------------------------------- /src/hooks/useSticky.js: -------------------------------------------------------------------------------- 1 | import { useEffect, useState, useRef } from "react"; 2 | 3 | function useSticky () { 4 | const [isSticky, setSticky] = useState(false); 5 | const element = useRef(null) 6 | 7 | const handleScroll = () => { 8 | window.scrollY > element.current.getBoundingClientRect().bottom 9 | ? setSticky(true) 10 | : setSticky(false); 11 | } 12 | 13 | // This function handle the scroll performance issue 14 | const debounce = (func, wait = 20, immediate = true) => { 15 | let timeOut; 16 | return () => { 17 | let context = this, 18 | args = arguments; 19 | const later = () => { 20 | timeOut = null; 21 | if (!immediate) func.apply(context, args); 22 | }; 23 | const callNow = immediate && !timeOut; 24 | clearTimeout(timeOut); 25 | timeOut = setTimeout(later, wait); 26 | if (callNow) func.apply(context, args); 27 | }; 28 | }; 29 | 30 | 31 | useEffect(() => { 32 | window.addEventListener("scroll", debounce(handleScroll)) 33 | return () => { 34 | window.removeEventListener("scroll", () => handleScroll); 35 | } 36 | }, [debounce, handleScroll]) 37 | 38 | 39 | return { isSticky, element } 40 | } 41 | 42 | export default useSticky 43 | -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /src/components/Header/Welcome.css: -------------------------------------------------------------------------------- 1 | .welcome { 2 | background-color: #1f1f1f; 3 | background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100%25' height='100%25' viewBox='0 0 1600 800'%3E%3Cg %3E%3Cpath fill='%23202020' d='M486 705.8c-109.3-21.8-223.4-32.2-335.3-19.4C99.5 692.1 49 703 0 719.8V800h843.8c-115.9-33.2-230.8-68.1-347.6-92.2C492.8 707.1 489.4 706.5 486 705.8z'/%3E%3Cpath fill='%23202020' d='M1600 0H0v719.8c49-16.8 99.5-27.8 150.7-33.5c111.9-12.7 226-2.4 335.3 19.4c3.4 0.7 6.8 1.4 10.2 2c116.8 24 231.7 59 347.6 92.2H1600V0z'/%3E%3Cpath fill='%23212121' d='M478.4 581c3.2 0.8 6.4 1.7 9.5 2.5c196.2 52.5 388.7 133.5 593.5 176.6c174.2 36.6 349.5 29.2 518.6-10.2V0H0v574.9c52.3-17.6 106.5-27.7 161.1-30.9C268.4 537.4 375.7 554.2 478.4 581z'/%3E%3Cpath fill='%23212121' d='M0 0v429.4c55.6-18.4 113.5-27.3 171.4-27.7c102.8-0.8 203.2 22.7 299.3 54.5c3 1 5.9 2 8.9 3c183.6 62 365.7 146.1 562.4 192.1c186.7 43.7 376.3 34.4 557.9-12.6V0H0z'/%3E%3Cpath fill='%23222222' d='M181.8 259.4c98.2 6 191.9 35.2 281.3 72.1c2.8 1.1 5.5 2.3 8.3 3.4c171 71.6 342.7 158.5 531.3 207.7c198.8 51.8 403.4 40.8 597.3-14.8V0H0v283.2C59 263.6 120.6 255.7 181.8 259.4z'/%3E%3Cpath fill='%23252525' d='M1600 0H0v136.3c62.3-20.9 127.7-27.5 192.2-19.2c93.6 12.1 180.5 47.7 263.3 89.6c2.6 1.3 5.1 2.6 7.7 3.9c158.4 81.1 319.7 170.9 500.3 223.2c210.5 61 430.8 49 636.6-16.6V0z'/%3E%3Cpath fill='%23292929' d='M454.9 86.3C600.7 177 751.6 269.3 924.1 325c208.6 67.4 431.3 60.8 637.9-5.3c12.8-4.1 25.4-8.4 38.1-12.9V0H288.1c56 21.3 108.7 50.6 159.7 82C450.2 83.4 452.5 84.9 454.9 86.3z'/%3E%3Cpath fill='%232c2c2c' d='M1600 0H498c118.1 85.8 243.5 164.5 386.8 216.2c191.8 69.2 400 74.7 595 21.1c40.8-11.2 81.1-25.2 120.3-41.7V0z'/%3E%3Cpath fill='%23303030' d='M1397.5 154.8c47.2-10.6 93.6-25.3 138.6-43.8c21.7-8.9 43-18.8 63.9-29.5V0H643.4c62.9 41.7 129.7 78.2 202.1 107.4C1020.4 178.1 1214.2 196.1 1397.5 154.8z'/%3E%3Cpath fill='%23333333' d='M1315.3 72.4c75.3-12.6 148.9-37.1 216.8-72.4h-723C966.8 71 1144.7 101 1315.3 72.4z'/%3E%3C/g%3E%3C/svg%3E"); 4 | background-attachment: fixed; 5 | background-size: cover; 6 | line-height: 1.8; 7 | height: 100vh; 8 | display: flex; 9 | justify-content: center; 10 | align-items: center; 11 | text-align: center; 12 | } 13 | .welcome--logo { 14 | width: 10rem; 15 | } 16 | 17 | .welcome--about { 18 | padding: 2rem; 19 | width: 50rem; 20 | color: #444; 21 | text-align: justify; 22 | margin: auto; 23 | } 24 | 25 | .welcome__cta-primary { 26 | background: #e74c3c; 27 | color: #fff; 28 | margin-top: 1rem; 29 | padding: 0.7rem 1.5rem; 30 | border: none; 31 | border-radius: 20px; 32 | font-weight: 700; 33 | } 34 | -------------------------------------------------------------------------------- /src/serviceWorker.js: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read https://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.0/8 are considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 20 | ) 21 | ); 22 | 23 | export function register(config) { 24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 25 | // The URL constructor is available in all browsers that support SW. 26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); 27 | if (publicUrl.origin !== window.location.origin) { 28 | // Our service worker won't work if PUBLIC_URL is on a different origin 29 | // from what our page is served on. This might happen if a CDN is used to 30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 31 | return; 32 | } 33 | 34 | window.addEventListener('load', () => { 35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 36 | 37 | if (isLocalhost) { 38 | // This is running on localhost. Let's check if a service worker still exists or not. 39 | checkValidServiceWorker(swUrl, config); 40 | 41 | // Add some additional logging to localhost, pointing developers to the 42 | // service worker/PWA documentation. 43 | navigator.serviceWorker.ready.then(() => { 44 | console.log( 45 | 'This web app is being served cache-first by a service ' + 46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA' 47 | ); 48 | }); 49 | } else { 50 | // Is not localhost. Just register service worker 51 | registerValidSW(swUrl, config); 52 | } 53 | }); 54 | } 55 | } 56 | 57 | function registerValidSW(swUrl, config) { 58 | navigator.serviceWorker 59 | .register(swUrl) 60 | .then(registration => { 61 | registration.onupdatefound = () => { 62 | const installingWorker = registration.installing; 63 | if (installingWorker == null) { 64 | return; 65 | } 66 | installingWorker.onstatechange = () => { 67 | if (installingWorker.state === 'installed') { 68 | if (navigator.serviceWorker.controller) { 69 | // At this point, the updated precached content has been fetched, 70 | // but the previous service worker will still serve the older 71 | // content until all client tabs are closed. 72 | console.log( 73 | 'New content is available and will be used when all ' + 74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' 75 | ); 76 | 77 | // Execute callback 78 | if (config && config.onUpdate) { 79 | config.onUpdate(registration); 80 | } 81 | } else { 82 | // At this point, everything has been precached. 83 | // It's the perfect time to display a 84 | // "Content is cached for offline use." message. 85 | console.log('Content is cached for offline use.'); 86 | 87 | // Execute callback 88 | if (config && config.onSuccess) { 89 | config.onSuccess(registration); 90 | } 91 | } 92 | } 93 | }; 94 | }; 95 | }) 96 | .catch(error => { 97 | console.error('Error during service worker registration:', error); 98 | }); 99 | } 100 | 101 | function checkValidServiceWorker(swUrl, config) { 102 | // Check if the service worker can be found. If it can't reload the page. 103 | fetch(swUrl, { 104 | headers: { 'Service-Worker': 'script' } 105 | }) 106 | .then(response => { 107 | // Ensure service worker exists, and that we really are getting a JS file. 108 | const contentType = response.headers.get('content-type'); 109 | if ( 110 | response.status === 404 || 111 | (contentType != null && contentType.indexOf('javascript') === -1) 112 | ) { 113 | // No service worker found. Probably a different app. Reload the page. 114 | navigator.serviceWorker.ready.then(registration => { 115 | registration.unregister().then(() => { 116 | window.location.reload(); 117 | }); 118 | }); 119 | } else { 120 | // Service worker found. Proceed as normal. 121 | registerValidSW(swUrl, config); 122 | } 123 | }) 124 | .catch(() => { 125 | console.log( 126 | 'No internet connection found. App is running in offline mode.' 127 | ); 128 | }); 129 | } 130 | 131 | export function unregister() { 132 | if ('serviceWorker' in navigator) { 133 | navigator.serviceWorker.ready.then(registration => { 134 | registration.unregister(); 135 | }); 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /src/assets/images/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | --------------------------------------------------------------------------------