├── .github └── workflows │ ├── gh-pages-publish.yml │ └── npm-publish.yml ├── .gitignore ├── .npmignore ├── .storybook ├── ComponentDemo.stories.tsx ├── HookDemo.stories.tsx ├── main.js └── preview.css ├── LICENSE ├── README.md ├── package.json ├── react-visibility.jpg ├── src ├── VisibilityObserver.tsx ├── index.ts └── useVisibility.ts └── tsconfig.json /.github/workflows/gh-pages-publish.yml: -------------------------------------------------------------------------------- 1 | name: GitHub Pages deploy 2 | on: 3 | push: 4 | branches: 5 | - main 6 | 7 | jobs: 8 | deploy-gh-pages: 9 | runs-on: ubuntu-20.04 10 | steps: 11 | - name: 📚 Checkout 12 | uses: actions/checkout@v2 13 | - name: 🟢 Setup Node 14 | uses: actions/setup-node@v2 15 | with: 16 | node-version: 16 17 | registry-url: "https://registry.npmjs.org" 18 | - name: Install dependencies 19 | run: npm install 20 | - name: Build Storybook 21 | run: npm run build:storybook 22 | - name: Deploy to GitHub Pages 23 | uses: Cecilapp/GitHub-Pages-deploy@v3 24 | env: 25 | GITHUB_TOKEN: ${{ secrets.ACCESS_TOKEN }} 26 | with: 27 | build_dir: storybook-static 28 | -------------------------------------------------------------------------------- /.github/workflows/npm-publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish to NPM 2 | 3 | on: 4 | release: 5 | types: [created] 6 | 7 | jobs: 8 | npm_publish: 9 | runs-on: ubuntu-20.04 10 | steps: 11 | - name: 📚 Checkout 12 | uses: actions/checkout@v2 13 | - name: 🟢 Setup Node 14 | uses: actions/setup-node@v2 15 | with: 16 | node-version: 14 17 | registry-url: "https://registry.npmjs.org" 18 | - name: 🔧 Install dependencies and build 19 | run: npm install && npm run build 20 | - name: 📦 Publish package on NPM 21 | run: npm publish 22 | env: 23 | NODE_AUTH_TOKEN: ${{secrets.NPM_AUTH_TOKEN}} 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Folders 2 | /node_modules 3 | package-lock.json 4 | /storybook-static 5 | /dist 6 | # Output of 'npm pack' 7 | *.tgz -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | # Folders 2 | node_modules 3 | package-lock.json 4 | .storybook 5 | src 6 | /storybook-static 7 | 8 | # Output of 'npm pack' 9 | *.tgz 10 | 11 | # Files 12 | .gitignore 13 | .github -------------------------------------------------------------------------------- /.storybook/ComponentDemo.stories.tsx: -------------------------------------------------------------------------------- 1 | import classNames from "classnames"; 2 | import { useState } from "react"; 3 | import { VisibilityObserver } from "../src"; 4 | 5 | export default { 6 | title: "reactjs-visibility", 7 | }; 8 | 9 | export const ComponentDemo = () => { 10 | const [visible, setVisible] = useState(false); 11 | 12 | return ( 13 |
14 |
17 |

{""}

18 | {visible &&

The sensor is visible

} 19 |

Scroll down

20 |
21 |

22 | The purpose of lorem ipsum is to create a natural looking block of text 23 | (sentence, paragraph, page, etc.) that doesn't distract from the layout. 24 | A practice not without controversy, laying out pages with meaningless 25 | filler text can be very useful when the focus is meant to be on design, 26 | not content. 27 |

28 | 29 |

30 | The passage experienced a surge in popularity during the 1960s when 31 | Letraset used it on their dry-transfer sheets, and again during the 90s 32 | as desktop publishers bundled the text with their software. Today it's 33 | seen all around the web; on templates, websites, and stock designs. Use 34 | our generator to get your own, or read on for the authoritative history 35 | of lorem ipsum. 36 |

37 | 38 |

39 | Until recently, the prevailing view assumed lorem ipsum was born as a 40 | nonsense text. “It's not Latin, though it looks like it, and it actually 41 | says nothing,” Before & After magazine answered a curious reader, “Its 42 | ‘words’ loosely approximate the frequency with which letters occur in 43 | English, which is why at a glance it looks pretty real.” 44 |

45 | 46 |

47 | Richard McClintock, a Latin scholar from Hampden-Sydney College, is 48 | credited with discovering the source behind the ubiquitous filler text. 49 | In seeing a sample of lorem ipsum, his interest was piqued by 50 | consectetur—a genuine, albeit rare, Latin word. Consulting a Latin 51 | dictionary led McClintock to a passage from De Finibus Bonorum et 52 | Malorum (“On the Extremes of Good and Evil”), a first-century B.C. text 53 | from the Roman philosopher Cicero. 54 |

55 |

56 | The purpose of lorem ipsum is to create a natural looking block of text 57 | (sentence, paragraph, page, etc.) that doesn't distract from the layout. 58 | A practice not without controversy, laying out pages with meaningless 59 | filler text can be very useful when the focus is meant to be on design, 60 | not content. 61 |

62 | 63 |

64 | The passage experienced a surge in popularity during the 1960s when 65 | Letraset used it on their dry-transfer sheets, and again during the 90s 66 | as desktop publishers bundled the text with their software. Today it's 67 | seen all around the web; on templates, websites, and stock designs. Use 68 | our generator to get your own, or read on for the authoritative history 69 | of lorem ipsum. 70 |

71 | 72 |

73 | Until recently, the prevailing view assumed lorem ipsum was born as a 74 | nonsense text. “It's not Latin, though it looks like it, and it actually 75 | says nothing,” Before & After magazine answered a curious reader, “Its 76 | ‘words’ loosely approximate the frequency with which letters occur in 77 | English, which is why at a glance it looks pretty real.” 78 |

79 | 80 |

81 | Richard McClintock, a Latin scholar from Hampden-Sydney College, is 82 | credited with discovering the source behind the ubiquitous filler text. 83 | In seeing a sample of lorem ipsum, his interest was piqued by 84 | consectetur—a genuine, albeit rare, Latin word. Consulting a Latin 85 | dictionary led McClintock to a passage from De Finibus Bonorum et 86 | Malorum (“On the Extremes of Good and Evil”), a first-century B.C. text 87 | from the Roman philosopher Cicero. 88 |

89 |

90 | The purpose of lorem ipsum is to create a natural looking block of text 91 | (sentence, paragraph, page, etc.) that doesn't distract from the layout. 92 | A practice not without controversy, laying out pages with meaningless 93 | filler text can be very useful when the focus is meant to be on design, 94 | not content. 95 |

96 | 97 |

98 | The passage experienced a surge in popularity during the 1960s when 99 | Letraset used it on their dry-transfer sheets, and again during the 90s 100 | as desktop publishers bundled the text with their software. Today it's 101 | seen all around the web; on templates, websites, and stock designs. Use 102 | our generator to get your own, or read on for the authoritative history 103 | of lorem ipsum. 104 |

105 | 106 |

107 | Until recently, the prevailing view assumed lorem ipsum was born as a 108 | nonsense text. “It's not Latin, though it looks like it, and it actually 109 | says nothing,” Before & After magazine answered a curious reader, “Its 110 | ‘words’ loosely approximate the frequency with which letters occur in 111 | English, which is why at a glance it looks pretty real.” 112 |

113 | 114 |

115 | Richard McClintock, a Latin scholar from Hampden-Sydney College, is 116 | credited with discovering the source behind the ubiquitous filler text. 117 | In seeing a sample of lorem ipsum, his interest was piqued by 118 | consectetur—a genuine, albeit rare, Latin word. Consulting a Latin 119 | dictionary led McClintock to a passage from De Finibus Bonorum et 120 | Malorum (“On the Extremes of Good and Evil”), a first-century B.C. text 121 | from the Roman philosopher Cicero. 122 |

123 | 124 | 125 |
126 |

Hey I am here

127 |
128 |
129 | 130 |

131 | The purpose of lorem ipsum is to create a natural looking block of text 132 | (sentence, paragraph, page, etc.) that doesn't distract from the layout. 133 | A practice not without controversy, laying out pages with meaningless 134 | filler text can be very useful when the focus is meant to be on design, 135 | not content. 136 |

137 | 138 |

139 | The passage experienced a surge in popularity during the 1960s when 140 | Letraset used it on their dry-transfer sheets, and again during the 90s 141 | as desktop publishers bundled the text with their software. Today it's 142 | seen all around the web; on templates, websites, and stock designs. Use 143 | our generator to get your own, or read on for the authoritative history 144 | of lorem ipsum. 145 |

146 | 147 |

148 | Until recently, the prevailing view assumed lorem ipsum was born as a 149 | nonsense text. “It's not Latin, though it looks like it, and it actually 150 | says nothing,” Before & After magazine answered a curious reader, “Its 151 | ‘words’ loosely approximate the frequency with which letters occur in 152 | English, which is why at a glance it looks pretty real.” 153 |

154 | 155 |

156 | Richard McClintock, a Latin scholar from Hampden-Sydney College, is 157 | credited with discovering the source behind the ubiquitous filler text. 158 | In seeing a sample of lorem ipsum, his interest was piqued by 159 | consectetur—a genuine, albeit rare, Latin word. Consulting a Latin 160 | dictionary led McClintock to a passage from De Finibus Bonorum et 161 | Malorum (“On the Extremes of Good and Evil”), a first-century B.C. text 162 | from the Roman philosopher Cicero. 163 |

164 |
165 | ); 166 | }; 167 | -------------------------------------------------------------------------------- /.storybook/HookDemo.stories.tsx: -------------------------------------------------------------------------------- 1 | import { useState } from "react"; 2 | import classNames from "classnames"; 3 | import { useVisibility, VisibilityObserver } from "../src/index"; 4 | import "./preview.css"; 5 | 6 | export default { 7 | title: "reactjs-visibility", 8 | }; 9 | 10 | export const HookDemo = () => { 11 | const { ref, visible } = useVisibility({}); 12 | return ( 13 |
14 |
17 |

useOnScreen()

18 | {visible &&

The sensor is visible

} 19 | 20 |

Scroll down

21 |
22 |

23 | The purpose of lorem ipsum is to create a natural looking block of text 24 | (sentence, paragraph, page, etc.) that doesn't distract from the layout. 25 | A practice not without controversy, laying out pages with meaningless 26 | filler text can be very useful when the focus is meant to be on design, 27 | not content. 28 |

29 | 30 |

31 | The passage experienced a surge in popularity during the 1960s when 32 | Letraset used it on their dry-transfer sheets, and again during the 90s 33 | as desktop publishers bundled the text with their software. Today it's 34 | seen all around the web; on templates, websites, and stock designs. Use 35 | our generator to get your own, or read on for the authoritative history 36 | of lorem ipsum. 37 |

38 | 39 |

40 | Until recently, the prevailing view assumed lorem ipsum was born as a 41 | nonsense text. “It's not Latin, though it looks like it, and it actually 42 | says nothing,” Before & After magazine answered a curious reader, “Its 43 | ‘words’ loosely approximate the frequency with which letters occur in 44 | English, which is why at a glance it looks pretty real.” 45 |

46 | 47 |

48 | Richard McClintock, a Latin scholar from Hampden-Sydney College, is 49 | credited with discovering the source behind the ubiquitous filler text. 50 | In seeing a sample of lorem ipsum, his interest was piqued by 51 | consectetur—a genuine, albeit rare, Latin word. Consulting a Latin 52 | dictionary led McClintock to a passage from De Finibus Bonorum et 53 | Malorum (“On the Extremes of Good and Evil”), a first-century B.C. text 54 | from the Roman philosopher Cicero. 55 |

56 |

57 | The purpose of lorem ipsum is to create a natural looking block of text 58 | (sentence, paragraph, page, etc.) that doesn't distract from the layout. 59 | A practice not without controversy, laying out pages with meaningless 60 | filler text can be very useful when the focus is meant to be on design, 61 | not content. 62 |

63 | 64 |

65 | The passage experienced a surge in popularity during the 1960s when 66 | Letraset used it on their dry-transfer sheets, and again during the 90s 67 | as desktop publishers bundled the text with their software. Today it's 68 | seen all around the web; on templates, websites, and stock designs. Use 69 | our generator to get your own, or read on for the authoritative history 70 | of lorem ipsum. 71 |

72 | 73 |

74 | Until recently, the prevailing view assumed lorem ipsum was born as a 75 | nonsense text. “It's not Latin, though it looks like it, and it actually 76 | says nothing,” Before & After magazine answered a curious reader, “Its 77 | ‘words’ loosely approximate the frequency with which letters occur in 78 | English, which is why at a glance it looks pretty real.” 79 |

80 | 81 |

82 | Richard McClintock, a Latin scholar from Hampden-Sydney College, is 83 | credited with discovering the source behind the ubiquitous filler text. 84 | In seeing a sample of lorem ipsum, his interest was piqued by 85 | consectetur—a genuine, albeit rare, Latin word. Consulting a Latin 86 | dictionary led McClintock to a passage from De Finibus Bonorum et 87 | Malorum (“On the Extremes of Good and Evil”), a first-century B.C. text 88 | from the Roman philosopher Cicero. 89 |

90 |

91 | The purpose of lorem ipsum is to create a natural looking block of text 92 | (sentence, paragraph, page, etc.) that doesn't distract from the layout. 93 | A practice not without controversy, laying out pages with meaningless 94 | filler text can be very useful when the focus is meant to be on design, 95 | not content. 96 |

97 | 98 |

99 | The passage experienced a surge in popularity during the 1960s when 100 | Letraset used it on their dry-transfer sheets, and again during the 90s 101 | as desktop publishers bundled the text with their software. Today it's 102 | seen all around the web; on templates, websites, and stock designs. Use 103 | our generator to get your own, or read on for the authoritative history 104 | of lorem ipsum. 105 |

106 | 107 |

108 | Until recently, the prevailing view assumed lorem ipsum was born as a 109 | nonsense text. “It's not Latin, though it looks like it, and it actually 110 | says nothing,” Before & After magazine answered a curious reader, “Its 111 | ‘words’ loosely approximate the frequency with which letters occur in 112 | English, which is why at a glance it looks pretty real.” 113 |

114 | 115 |

116 | Richard McClintock, a Latin scholar from Hampden-Sydney College, is 117 | credited with discovering the source behind the ubiquitous filler text. 118 | In seeing a sample of lorem ipsum, his interest was piqued by 119 | consectetur—a genuine, albeit rare, Latin word. Consulting a Latin 120 | dictionary led McClintock to a passage from De Finibus Bonorum et 121 | Malorum (“On the Extremes of Good and Evil”), a first-century B.C. text 122 | from the Roman philosopher Cicero. 123 |

124 | 125 |
126 |

Hey I am here

127 |
128 | 129 |

130 | The purpose of lorem ipsum is to create a natural looking block of text 131 | (sentence, paragraph, page, etc.) that doesn't distract from the layout. 132 | A practice not without controversy, laying out pages with meaningless 133 | filler text can be very useful when the focus is meant to be on design, 134 | not content. 135 |

136 | 137 |

138 | The passage experienced a surge in popularity during the 1960s when 139 | Letraset used it on their dry-transfer sheets, and again during the 90s 140 | as desktop publishers bundled the text with their software. Today it's 141 | seen all around the web; on templates, websites, and stock designs. Use 142 | our generator to get your own, or read on for the authoritative history 143 | of lorem ipsum. 144 |

145 | 146 |

147 | Until recently, the prevailing view assumed lorem ipsum was born as a 148 | nonsense text. “It's not Latin, though it looks like it, and it actually 149 | says nothing,” Before & After magazine answered a curious reader, “Its 150 | ‘words’ loosely approximate the frequency with which letters occur in 151 | English, which is why at a glance it looks pretty real.” 152 |

153 | 154 |

155 | Richard McClintock, a Latin scholar from Hampden-Sydney College, is 156 | credited with discovering the source behind the ubiquitous filler text. 157 | In seeing a sample of lorem ipsum, his interest was piqued by 158 | consectetur—a genuine, albeit rare, Latin word. Consulting a Latin 159 | dictionary led McClintock to a passage from De Finibus Bonorum et 160 | Malorum (“On the Extremes of Good and Evil”), a first-century B.C. text 161 | from the Roman philosopher Cicero. 162 |

163 |
164 | ); 165 | }; 166 | -------------------------------------------------------------------------------- /.storybook/main.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | stories: ["./*.stories.tsx"], 3 | reactOptions: { 4 | fastRefresh: true, 5 | strictMode: true, 6 | }, 7 | }; 8 | -------------------------------------------------------------------------------- /.storybook/preview.css: -------------------------------------------------------------------------------- 1 | body { 2 | font-family: Arial, Helvetica, sans-serif; 3 | font-size: 16px; 4 | } 5 | 6 | p { 7 | line-height: 1.8rem; 8 | } 9 | 10 | .container{ 11 | max-width: 650px; 12 | margin: 0 auto; 13 | } 14 | 15 | .header { 16 | width: 100%; 17 | color: #fff; 18 | padding: 3px 10px; 19 | position: sticky; 20 | top: 0; 21 | left: 0; 22 | display: flex; 23 | align-items: center; 24 | justify-content: space-between; 25 | font-family: monospace; 26 | background-color: tomato; 27 | } 28 | 29 | .header--sensor-visible { 30 | background-color: green !important; 31 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 KingRayhan 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # React Visibility 2 | 3 | Detect when an element is becoming visible or hidden on the page. 4 | 5 |
6 | 7 |
8 | 9 | [![GitHub Pages deploy](https://github.com/kingRayhan/reactjs-visibility/actions/workflows/gh-pages-publish.yml/badge.svg)](https://github.com/kingRayhan/reactjs-visibility/actions/workflows/gh-pages-publish.yml) 10 | [![Publish to NPM](https://github.com/kingRayhan/reactjs-visibility/actions/workflows/npm-publish.yml/badge.svg)](https://github.com/kingRayhan/reactjs-visibility/actions/workflows/npm-publish.yml) 11 | 12 | ![npm bundle size](https://img.shields.io/bundlephobia/min/reactjs-visibility) 13 | ![npm bundle size](https://img.shields.io/bundlephobia/minzip/reactjs-visibility) 14 | [![npm downloads](https://img.shields.io/npm/dt/@kingrayhan/react-onscreen)](https://www.npmjs.com/package/reactjs-visibility) 15 | [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/kingrayhan/reactjs-visibility/blob/master/LICENSE) 16 | 17 | ## [See in action](https://kingrayhan.github.io/reactjs-visibility/) 18 | 19 | ### Installation 20 | 21 | ```bash 22 | npm install reactjs-visibility 23 | ``` 24 | 25 | > ⚠️ This plugin uses the Intersection Observer API that is not supported in every browser (currently supported in Edge, Firefox and Chrome). You need to include a polyfill to make it work on incompatible browsers. 26 | 27 | ### Detech visibility with `` component 28 | 29 | ```jsx 30 | import React from "react"; 31 | import { VisibilityObserver } from "reactjs-visibility"; 32 | 33 | const App = () => { 34 | const handleChangeVisibility = (visible) => { 35 | if (visible) { 36 | alert("I am now visible"); 37 | } 38 | }; 39 | 40 | const options = { 41 | rootMargin: "200px", 42 | }; 43 | 44 | return ( 45 |
46 |

47 | Lorem ipsum dolor sit, amet consectetur adipisicing elit. Magni nam 48 | exercitationem sit alias perferendis, odit ex optio iure assumenda! 49 | Voluptatum, nulla. Assumenda iusto nesciunt adipisci totam repellat id 50 | excepturi minima. 51 |

52 | 53 | 57 | Loadmore... 58 | 59 |
60 | ); 61 | }; 62 | ``` 63 | 64 | ### Detech visibility with `useVisibility()` Hook 65 | 66 | **Example 1** 67 | 68 | ```jsx 69 | import React from "react"; 70 | import { useVisibility } from "reactjs-visibility"; 71 | 72 | const App = () => { 73 | const handleChangeVisibility = (visible) => { 74 | if (visible) { 75 | alert("I am now visible"); 76 | } 77 | }; 78 | 79 | const options = {}; 80 | 81 | const { ref, visible } = useVisibility({ 82 | onChangeVisibility: handleChangeVisibility, 83 | options, 84 | }); 85 | 86 | console.log(visible); 87 | 88 | return ( 89 |
90 |

91 | Lorem ipsum dolor sit, amet consectetur adipisicing elit. Magni nam 92 | exercitationem sit alias perferendis, odit ex optio iure assumenda! 93 | Voluptatum, nulla. Assumenda iusto nesciunt adipisci totam repellat id 94 | excepturi minima. 95 |

96 | 97 |
Loadmore...
98 |
99 | ); 100 | }; 101 | ``` 102 | 103 | **Example 2** 104 | 105 | ```jsx 106 | import React from "react"; 107 | import { useVisibility } from "reactjs-visibility"; 108 | 109 | const App = () => { 110 | const { ref, visible } = useVisibility(); 111 | 112 | useEffect(() => { 113 | if (visible) { 114 | alert("I am now visible"); 115 | } 116 | }, [visible]); 117 | 118 | return ( 119 |
120 |

121 | Lorem ipsum dolor sit, amet consectetur adipisicing elit. Magni nam 122 | exercitationem sit alias perferendis, odit ex optio iure assumenda! 123 | Voluptatum, nulla. Assumenda iusto nesciunt adipisci totam repellat id 124 | excepturi minima. 125 |

126 | 127 |
Loadmore...
128 |
129 | ); 130 | }; 131 | ``` 132 | 133 | ## Options 134 | 135 | It's possible to pass the [IntersectionObserver `options` object](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/IntersectionObserver#Parameters) using the `intersection` 136 | 137 | ### License 138 | 139 | MIT license, Copyright (c) KingRayhan. For more information see `LICENSE`. 140 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "reactjs-visibility", 3 | "version": "0.1.4", 4 | "description": "Detect when an element is becoming visible or hidden on the page.", 5 | "main": "dist/index.js", 6 | "scripts": { 7 | "build": "tsdx build", 8 | "publish": "npm publish --access public", 9 | "release": "semantic-release", 10 | "dev:storybook": "start-storybook", 11 | "build:storybook": "build-storybook" 12 | }, 13 | "keywords": [ 14 | "react", 15 | "react-visibility", 16 | "visibility", 17 | "visibility-sensor", 18 | "visibility-sensor-react", 19 | "visibility-sensor-react-native", 20 | "intersaction-observer", 21 | "interaction-observer", 22 | "interaction-observer-react", 23 | "interaction-observer-react-native", 24 | "interaction-observer-react-native-web" 25 | ], 26 | "author": { 27 | "name": "King Rayhan", 28 | "email": "rayhan.dev.bd@gmail.com", 29 | "url": "https://www.github.com/kingrayhan" 30 | }, 31 | "repository": "kingRayhan/reactjs-visibility", 32 | "license": "MIT", 33 | "peerDependencies": { 34 | "react": ">=16", 35 | "react-dom": ">=16" 36 | }, 37 | "devDependencies": { 38 | "@storybook/react": "^6.3.6", 39 | "@types/react": "^17.0.16", 40 | "@types/react-dom": "^17.0.9", 41 | "classnames": "^2.3.1", 42 | "tsdx": "^0.13.3", 43 | "semantic-release": "^19.0.2" 44 | }, 45 | "release": { 46 | "branches": [ 47 | "main" 48 | ] 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /react-visibility.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kingRayhan/reactjs-visibility/1709fb649b7e7b00569359d3981b77a180e27b9f/react-visibility.jpg -------------------------------------------------------------------------------- /src/VisibilityObserver.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import useVisibility from "./useVisibility"; 3 | 4 | interface ObserverVisibilityComponentInterface { 5 | onChangeVisibility: (visibility: boolean) => void; 6 | options?: IntersectionObserverInit; 7 | children?: JSX.Element | JSX.Element[]; 8 | } 9 | 10 | const VisibilityObserver = (props: ObserverVisibilityComponentInterface) => { 11 | const handleOnScreen = (visible: boolean) => { 12 | if (props.onChangeVisibility) { 13 | props.onChangeVisibility(visible); 14 | } 15 | }; 16 | 17 | const { ref } = useVisibility({ 18 | options: props.options, 19 | onChangeVisibility: handleOnScreen, 20 | }); 21 | 22 | return ( 23 | // @ts-ignore 24 |
{props.children}
25 | ); 26 | }; 27 | 28 | export default VisibilityObserver; 29 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export {default as useVisibility} from './useVisibility' 2 | export {default as VisibilityObserver} from './VisibilityObserver' -------------------------------------------------------------------------------- /src/useVisibility.ts: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useRef, useState } from "react"; 2 | 3 | interface useOnScreenInterface { 4 | onChangeVisibility?: (visibility: boolean) => void; 5 | options?: IntersectionObserverInit; 6 | } 7 | 8 | interface useVisibilityReturnType { 9 | ref: React.MutableRefObject; 10 | visible: Boolean; 11 | } 12 | 13 | const useVisibility = (args: useOnScreenInterface): useVisibilityReturnType => { 14 | const ref = useRef(); 15 | const [visible, setVisible] = useState(false); 16 | 17 | const handleIntersectionObserver: IntersectionObserverCallback = ([ 18 | entry, 19 | ]) => { 20 | setVisible(entry.isIntersecting); 21 | 22 | if (args?.onChangeVisibility) { 23 | args.onChangeVisibility(entry.isIntersecting); 24 | } 25 | }; 26 | 27 | useEffect(() => { 28 | const observer = new IntersectionObserver( 29 | handleIntersectionObserver, 30 | args?.options 31 | ); 32 | 33 | if (ref.current) { 34 | // @ts-ignore 35 | observer.observe(ref.current); 36 | } 37 | 38 | return () => { 39 | if (ref.current) { 40 | // @ts-ignore 41 | observer.unobserve(ref.current); 42 | } 43 | }; 44 | }, [ref]); 45 | 46 | return { ref, visible }; 47 | }; 48 | 49 | export default useVisibility; 50 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | // see https://www.typescriptlang.org/tsconfig to better understand tsconfigs 3 | "include": [ 4 | "src", 5 | "types" 6 | ], 7 | "compilerOptions": { 8 | "module": "esnext", 9 | "lib": [ 10 | "dom", 11 | "esnext" 12 | ], 13 | "importHelpers": true, 14 | // output .d.ts declaration files for consumers 15 | "declaration": true, 16 | // output .js.map sourcemap files for consumers 17 | "sourceMap": true, 18 | // match output dir to input dir. e.g. dist/index instead of dist/src/index 19 | "rootDir": "./src", 20 | // stricter type-checking for stronger correctness. Recommended by TS 21 | "strict": true, 22 | // linter checks for common issues 23 | "noImplicitReturns": true, 24 | "noFallthroughCasesInSwitch": true, 25 | // noUnused* overlap with @typescript-eslint/no-unused-vars, can disable if duplicative 26 | "noUnusedParameters": true, 27 | // use Node's module resolution algorithm, instead of the legacy TS one 28 | "moduleResolution": "node", 29 | // transpile JSX to React.createElement 30 | "jsx": "react", 31 | // interop between ESM and CJS modules. Recommended by TS 32 | "esModuleInterop": true, 33 | // significant perf increase by skipping checking .d.ts files, particularly those in node_modules. Recommended by TS 34 | "skipLibCheck": true, 35 | // error out if import and file system have a casing mismatch. Recommended by TS 36 | "forceConsistentCasingInFileNames": true, 37 | // `tsdx build` ignores this option, but it is commonly used when type-checking separately with `tsc` 38 | "noEmit": true, 39 | } 40 | } --------------------------------------------------------------------------------