├── .babelrc ├── .editorconfig ├── .eslintignore ├── .github └── FUNDING.yml ├── .gitignore ├── .nvmrc ├── .travis.yml ├── CHANGELOG.md ├── LICENSE ├── README.md ├── assets └── logo.png ├── package.json ├── react-sizeme.d.ts ├── rollup-min.config.js ├── rollup.config.js ├── src ├── __tests__ │ ├── component.test.js │ ├── typescript.test.js │ ├── typescript │ │ ├── component.tsx │ │ ├── hoc.tsx │ │ └── tsconfig.json │ └── with-size.test.js ├── component.js ├── index.js ├── resize-detector.js └── with-size.js ├── tools ├── .eslintrc ├── scripts │ └── build.js └── utils.js ├── wallaby.js └── yarn.lock /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | [ 4 | "@babel/preset-env", 5 | { 6 | "targets": { 7 | "node": true 8 | } 9 | } 10 | ], 11 | "@babel/preset-react" 12 | ], 13 | "plugins": ["@babel/plugin-proposal-class-properties"] 14 | } 15 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | charset = utf-8 7 | end_of_line = lf 8 | indent_size = 2 9 | indent_style = space 10 | insert_final_newline = true 11 | trim_trailing_whitespace = true 12 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | commonjs/ 3 | coverage/ 4 | umd/ 5 | src/__tests__/typescript/ 6 | *.ts -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: # ctrlplusb 5 | open_collective: controlplusb 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | 5 | # Dependencies 6 | node_modules 7 | 8 | # Debug log from npm 9 | npm-debug.log 10 | 11 | # Jest 12 | coverage 13 | 14 | # Build output 15 | dist 16 | -------------------------------------------------------------------------------- /.nvmrc: -------------------------------------------------------------------------------- 1 | 14 2 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: node_js 3 | cache: 4 | yarn: true 5 | directories: 6 | - node_modules 7 | node_js: 8 | - '14' 9 | script: 10 | - npm run lint 11 | - npm run build 12 | after_success: 13 | # Deploy code coverage report to codecov.io 14 | - npm run test:coverage:deploy 15 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | We follow semantic versioning. 2 | 3 | See the [releases](https://github.com/ctrlplusb/react-sizeme/releases) page on 4 | GitHub for information regarding each release. 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Sean Matheson 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 |
2 | 3 |
4 |
5 |
Make your React Components aware of their width and/or height!
6 | 7 | 8 |9 | 10 | [](http://npm.im/react-sizeme) 11 | [](http://opensource.org/licenses/MIT) 12 | [](https://travis-ci.org/ctrlplusb/react-sizeme) 13 | [](https://codecov.io/github/ctrlplusb/react-sizeme) 14 | 15 | - Hyper Responsive Components! 16 | - Performant. 17 | - Easy to use. 18 | - Extensive browser support. 19 | - Supports functional and class Component types. 20 | - Tiny bundle size. 21 | - Demo: https://4mkpc.csb.app/ 22 | 23 | Use it via the render prop pattern (supports `children` or `render` prop): 24 | 25 | ```javascript 26 | import { SizeMe } from 'react-sizeme' 27 | 28 | function MyApp() { 29 | return
46 | 47 | --- 48 | 49 | ## TOCs 50 | 51 | - [Intro](https://github.com/ctrlplusb/react-sizeme#intro) 52 | - [Installation](https://github.com/ctrlplusb/react-sizeme#installation) 53 | - [Configuration](https://github.com/ctrlplusb/react-sizeme#configuration) 54 | - [Component Usage](https://github.com/ctrlplusb/react-sizeme#component-usage) 55 | - [HOC Usage](https://github.com/ctrlplusb/react-sizeme#hoc-usage) 56 | - [`onSize` callback alternative usage](https://github.com/ctrlplusb/react-sizeme#onsize-callback-alternative-usage) 57 | - [Under the hood](https://github.com/ctrlplusb/react-sizeme#under-the-hood) 58 | - [Examples](#examples) 59 | - [Loading different child components based on size](#loading-different-child-components-based-on-size) 60 | - [Server Side Rendering](https://github.com/ctrlplusb/react-sizeme#server-side-rendering) 61 | - [Extreme Appreciation](https://github.com/ctrlplusb/react-sizeme#extreme-appreciation) 62 | - [Backers](https://github.com/ctrlplusb/react-sizeme#backers) 63 | 64 |
65 | 66 | --- 67 | 68 | ## Intro 69 | 70 | Give your Components the ability to have render logic based on their height and/or width. Responsive design on the Component level. This allows you to create highly reusable components that can adapt to wherever they are rendered. 71 | 72 | Check out a working demo here: https://4mkpc.csb.app/ 73 | 74 |
75 | 76 | --- 77 | 78 | ## Installation 79 | 80 | Firstly, ensure you have the required peer dependencies: 81 | 82 | ```bash 83 | npm install react react-dom 84 | ``` 85 | 86 | > **Note:** We require >=react@0.14.0 and >=react-dom@0.14.0 87 | 88 | ```bash 89 | npm install react-sizeme 90 | ``` 91 | 92 |
93 | 94 | --- 95 | 96 | ## Configuration 97 | 98 | The following configuration options are available. Please see the usage docs for how to pass these configuration values into either the [component](#component-usage) or [higher order function](#hoc-usage). 99 | 100 | - `monitorWidth` (_boolean_, **default**: true) 101 | 102 | If true, then any changes to your Components rendered width will cause an recalculation of the "size" prop which will then be be passed into your Component. 103 | 104 | - `monitorHeight` (_boolean_, **default**: false) 105 | 106 | If true, then any changes to your Components rendered height will cause an 107 | recalculation of the "size" prop which will then be be passed into 108 | your Component. 109 | 110 | > PLEASE NOTE: that this is set to `false` by default 111 | 112 | - `refreshRate` (_number_, **default**: 16) 113 | 114 | The maximum frequency, in milliseconds, at which size changes should be recalculated when changes in your Component's rendered size are being detected. This should not be set to lower than 16. 115 | 116 | - `refreshMode` (_string_, **default**: 'throttle') 117 | 118 | The mode in which refreshing should occur. Valid values are "debounce" and "throttle". 119 | 120 | "throttle" will eagerly measure your component and then wait for the refreshRate to pass before doing a new measurement on size changes. 121 | 122 | "debounce" will wait for a minimum of the refreshRate before it does a measurement check on your component. 123 | 124 | "debounce" can be useful in cases where your component is animated into the DOM. 125 | 126 | > NOTE: When using "debounce" mode you may want to consider disabling the placeholder as this adds an extra delay in the rendering time of your component. 127 | 128 | - `noPlaceholder` (_boolean_, **default**: false) 129 | 130 | By default we render a "placeholder" component initially so we can try and "prefetch" the expected size for your component. This is to avoid any unnecessary deep tree renders. If you feel this is not an issue for your component case and you would like to get an eager render of 131 | your component then disable the placeholder using this config option. 132 | 133 | > NOTE: You can set this globally. See the docs on first render. 134 | 135 |
136 | 137 | --- 138 | 139 | ## Component Usage 140 | 141 | We provide a "render props pattern" based component. You can import it like so: 142 | 143 | ```javascript 144 | import { SizeMe } from 'react-sizeme' 145 | ``` 146 | 147 | You then provide it either a `render` or `children` prop containing a function/component that will receive a `size` prop (an object with `width` and `height` properties): 148 | 149 | ```javascript 150 |
170 | 171 | --- 172 | 173 | ## HOC Usage 174 | 175 | We provide you with a higher order component function called `withSize`. You can import it like so: 176 | 177 | ```javascript 178 | import { withSize } from 'react-sizeme' 179 | ``` 180 | 181 | Firstly, you have to call the `withSize` function, passing in an optional [configuration](#configuration) object should you wish to customise the behaviour: 182 | 183 | ```javascript 184 | const withSizeHOC = withSize() 185 | ``` 186 | 187 | You can then use the returned Higher Order Component to decorate any of your existing Components with the size awareness ability: 188 | 189 | ```javascript 190 | const SizeAwareComponent = withSizeHOC(MyComponent) 191 | ``` 192 | 193 | Your component will then receive a `size` prop (an object with `width` and `height` properties). 194 | 195 | > Note that the values could be undefined based on the configuration you provided (e.g. you explicitly do not monitor either of the dimensions) 196 | 197 | Below is a full example: 198 | 199 | ```javascript 200 | import { withSize } from 'react-sizeme' 201 | 202 | class MyComponent extends Component { 203 | render() { 204 | const { width, height } = this.props.size 205 | 206 | return ( 207 |
252 | 253 | --- 254 | 255 | ## Under the hood 256 | 257 | It can be useful to understand the rendering workflow should you wish to debug any issues we may be having. 258 | 259 | In order to size your component we have a bit of a chicken/egg scenario. We can't know the width/height of your Component until it is rendered. This can lead wasteful rendering cycles should you choose to render your components based on their width/height. 260 | 261 | Therefore for the first render of your component we actually render a lightweight placeholder in place of your component in order to obtain the width/height. If your component was being passed a `className` or `style` prop then these will be applied to the placeholder so that it can more closely resemble your actual components dimensions. 262 | 263 | So the first dimensions that are passed to your component may not be "correct" dimensions, however, it should quickly receive the "correct" dimensions upon render. 264 | 265 | Should you wish to avoid the render of a placeholder and have an eager render of your component then you can use the `noPlaceholder` configuration option. Using this configuration value your component will be rendered directly, however, the `size` prop may contain `undefined` for width and height until your component completes its first render. 266 | 267 |
268 | 269 | --- 270 | 271 | ## Examples 272 | 273 | ### Loading different child components based on size 274 | 275 | ```javascript 276 | import React from 'react' 277 | import LargeChildComponent from './LargeChildComponent' 278 | import SmallChildComponent from './SmallChildComponent' 279 | import sizeMe from 'react-sizeme' 280 | 281 | function MyComponent(props) { 282 | const { width, height } = props.size 283 | 284 | const ToRenderChild = height > 600 ? LargeChildComponent : SmallChildComponent 285 | 286 | return ( 287 |
302 | 303 | --- 304 | 305 | ## Server Side Rendering 306 | 307 | Okay, I am gonna be up front here and tell you that using this library in an SSR context is most likely a bad idea. If you insist on doing so you then you should take the time to make yourself fully aware of any possible repercussions you application may face. 308 | 309 | A standard `sizeMe` configuration involves the rendering of a placeholder component. After the placeholder is mounted to the DOM we extract it's dimension information and pass it on to your actual component. We do this in order to avoid any unnecessary render cycles for possibly deep component trees. Whilst this is useful for a purely client side set up, this is less than useful for an SSR context as the delivered page will contain empty placeholders. Ideally you want actual content to be delivered so that users without JS can still have an experience, or SEO bots can scrape your website. 310 | 311 | To avoid the rendering of placeholders in this context you can make use of the `noPlaceholders` global configuration value. Setting this flag will disables any placeholder rendering. Instead your wrapped component will be rendered directly - however it's initial render will contain no values within the `size` prop (i.e. `width`, and `height` will be `null`). 312 | 313 | ```javascript 314 | import sizeMe from 'react-sizeme' 315 | 316 | // This is a global variable. i.e. will be the default for all instances. 317 | sizeMe.noPlaceholders = true 318 | ``` 319 | 320 | > Note: if you only partialy server render your application you may want to use the component level configuration that allows disabling placeholders per component (e.g. `sizeMe({ noPlaceholder: true })`) 321 | 322 | It is up to you to decide how you would like to initially render your component then. When your component is sent to the client and mounted to the DOM `SizeMe` will calculate and send the dimensions to your component as normal. I suggest you tread very carefully with how you use this updated information and do lots of testing using various screen dimensions. Try your best to avoid unnecessary re-rendering of your components, for the sake of your users. 323 | 324 | If you come up with any clever strategies for this please do come share them with us! :) 325 | 326 |
327 | 328 | --- 329 | 330 | ## Extreme Appreciation! 331 | 332 | We make use of the awesome [element-resize-detector](https://github.com/wnr/element-resize-detector) library. This library makes use of an scroll/object based event strategy which outperforms window resize event listening dramatically. The original idea for this approach comes from another library, namely [css-element-queries](https://github.com/marcj/css-element-queries) by Marc J. Schmidt. I recommend looking into these libraries for history, specifics, and more examples. I love them for the work they did, whithout which this library would not be possible. :sparkling_heart: 333 | 334 |
335 | 336 | --- 337 | 338 | ## Backers 339 | 340 | Thank goes to all our backers! [[Become a backer](https://opencollective.com/controlplusb#backer)]. 341 | 342 | 343 |
( 39 | component: ComponentType
,
40 | ) => ComponentType (
48 | component: ComponentType ,
49 | ) => ComponentType