digidem / react-dimensions Goto Github PK
View Code? Open in Web Editor NEW[Looking for maintainers]
Home Page: http://lab.digital-democracy.org/react-dimensions/
[Looking for maintainers]
Home Page: http://lab.digital-democracy.org/react-dimensions/
simple usecase
using react-popout (https://github.com/JakeGinnivan/react-popout) to tear off components into popout windows, which basically unmounts it and then re-mounts it into a new window and a new document.
the problem is this code: https://github.com/digidem/react-dimensions/blob/master/index.jsx#L110
window.addEventListener('resize', this.onResize, false)
... may resolve the window object too early and to the parent (original window), therefore adding the event to the wrong one.
subsequent resizes of the popout window do not trigger the resize and dimensions do not update but if the popout.opener gets resized, it fixes the popout dimensions.
The "containerStyle' and "className" options no longer do anything (since this commit), but are still included in the readme
It seems that everytime the flex layout changes, render
is called multiple times. And a bunch of times containerWidth
and containerHeight
are undefined. Everytime, in the last render-call, everything is fine and it works as intended.
This leads to a whole bunch of warnings of the type: Wrapper div has no height or width, try overriding style with
containerStyleoption
.
This happens even if I do not set 'elementResize' to true!
On IE11, when the dev tool is opened, an exception is thrown in defaultGetWidth
because element
is null
:
function defaultGetWidth(element) {
return element.clientWidth;
}
We no longer use this module in any of our code, and don't have time to maintain it. I'm happy to transfer this repo to someone or add maintainers.
I've just started using react-dimensions
and ran into a problem when using it in a flexbox layout. The wrapped <div>
was taking more space than I expected.
I was a bit surprised that react-dimensions
wrapped my <div>
with a <div>
of its own that had an inline style set to ``width:100%; height:100%`.
On first glance, it feels wrong for react-dimensions
to affect the layout.
Could we do something like reach up into DOM and get the actual parent instead?
ReactDOM.findDOMNode(this).parentNode
What do you think? Is there some reason that we couldn't get rid of the extra <div>
?
This SO answer seems relevant: http://stackoverflow.com/a/32855967/332048
We are anticipating an issue where having multiple components wrapped with Dimensions will start to cause performance issues. We should consider refactoring so that there is a single 'resize' event listener on window that triggers all Dimension-wrapped components to update their dimensions.
Would you accept a pull request if we had time to work on this? Also would you have time to work on this soon?
The compatibility documentation was not found
Normally, when the component is unmounted, window.removeEventListener is called for the resize handler. If, however, you are using the 'elementResize' config option, the handler can end up being called after the component is unmounted.
Perhaps adding a check in the getWidth function to see if the element still exists could make this safer?
given this code, how would you make the table responsive?
import React from 'react'
import {Table, Column, Cell} from 'fixed-data-table';
export default class Data extends React.Component {
render() {
return (
<div style={{width:'100%'}}>
<Table
rowHeight={50}
rowsCount={10}
width={600}
height={500}
headerHeight={30}>
<Column
header={<Cell>First Name</Cell>}
cell={<Cell>mama</Cell>}
fixed={true}
width={100}
/>
<Column
header={<Cell>Sentence! (flexGrow greediness=2)</Cell>}
cell={<Cell>chacha</Cell>}
flexGrow={2}
width={200}
/>
<Column
header={<Cell>Company (flexGrow greediness=1)</Cell>}
cell={<Cell>nana</Cell>}
flexGrow={1}
width={200}
/>
<Column
width={100}
header={<Cell>Last Name</Cell>}
cell={<Cell>sasa</Cell>}
/>
</Table>
</div>
)
}
}
I want to render a react app to a string and am using the ReadDOMServer to do so:
ReactDOMServer.renderToStaticMarkup(<EditorComponent store={this.props.store} id={this.props.id}` />)
However, I have a component that is wrapped by dimensions:
class Editable extends Component {
// ...
}
export default dimensions()(Editable)
With the dimensions decorator in there, the ReactDOMServer stops rendering all children there. Markup looks something like this:
<div>
<div style="width:100%;height:100%;padding:0;border:0;"></div>
</div>
while it should look something like this:
<div>
<div style="width:100%;height:100%;padding:0;border:0;">
<p> cool text </p>
</div>
</div>
Removing the dimensions()
decorator yields the desired result but breaks other logic that depends on dimensions:
<div>
<p> cool text </p>
</div>
I'd like to use the className option you added in a recent version, but despite being in the readme, it isn't yet available in 1.2.0 on npm.
Are you planning to release a new version soon?
Thanks
Would be great to provide the same API than https://github.com/bvaughn/react-virtualized/blob/master/docs/AutoSizer.md#prop-types (Same implementation / different interface)
One of my use cases is doing the size measurement on a single direction.
We would like to add an alwaysRender
boolean options to Dimensions so that the markup can be generated when the element is not displayed.
If you use Dimensions
to wrap a stateless functional component it complains but still seems to work.
const SomebodyCaresAboutDimensions = ({containerWidth} => (
<div>
width: {containerWidth}
</div>
));
export default Dimensions()(SomebodyCaresAboutDimensions);
will give
Warning: Stateless function components cannot be given refs (See ref "wrappedInstance" in SomebodyCaresAboutDimensions created by DimensionsHOC). Attempts to access this ref will fail.
The requestAnimationFrame
API only have 90% rate adoption. E.g. it's not supported on IE9.
I'm wondering if adding a polyfill here would make sense.
At least, the browser support should be documented.
Hi Guys,
We are experimenting away with this HOC component at the moment. Looks like it fits the bill nicely :-) Good stuff!
One thing that we have found though. We have a 3rd party library which is loading into a DIV. When the DIV is initially drawn on page, it has a height of 0px. When the library loads in and attaches to that DIV, the HOC component containerHeight property is not updated for some reason.
This might be a bug in our implementation, but failing that, is there a way to manually trigger a resize event here?
Thanks
Cam
The new version of React was released today (https://facebook.github.io/react/blog/2016/04/07/react-v15.html), but when I update my package.json to set react
and react-dom
to 15.0.0
, I get this error during updating:
$ npm install
- [email protected] node_modules\base62
- [email protected] node_modules\esprima-fb
- [email protected] node_modules\jstransform
- [email protected] node_modules\envify
[email protected] C:\Users\Kyle Getz\Work\event-viewer
+-- UNMET PEER DEPENDENCY [email protected]
| `-- [email protected]
| `-- [email protected]
| +-- [email protected]
| | +-- [email protected]
| | | `-- [email protected]
| | `-- [email protected]
| `-- [email protected]
`-- UNMET PEER DEPENDENCY [email protected]
npm WARN optional Skipping failed optional dependency /chokidar/fsevents:
npm WARN notsup Not compatible with your operating system or architecture: [email protected]
npm WARN [email protected] requires a peer of react@^0.14.0 but none was installed.
npm WARN [email protected] requires a peer of react-dom@^0.14.0 but none was installed.
npm ERR! code 1
Is this an issue with react-dimensions?
<div className='viewport'>
<div className='foo'>
<div className='bar'>
<Component />
</div>
</div>
</div>
.viewport {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
display: flex;
flex-direction: column;
}
.foo {
display: flex;
flex-direction: row;
flex-grow: 1;
}
.bar {
display: flex;
flex-direction: column;
flex-grow: 1;
}
With this setup, react-dimensions
will make component grow, but will not make it shrink. This is because <Component />
gets fixed width that .bar
container will respect (.foo
contents will overflow).
The only way I found I can fix this is by adding max-width: -webkit-fill-available
to the .bar
style.
There doesn't seem to be any way around this warning (it even throws in the example). It is thrown on the first render because the state is not yet updated after componentDidMount
.
Any ideas on how to avoid or silence it?
To use this module within svg, we need to be able to use <g>
instead of <div>
for wrappers.
Make
return (
<div style={wrapperStyle} ref='wrapper'>
Currently the wrapped component displays _class
in the react inspector
Could be as simple as this:
return class extends React.Component {
static displayName = `Dimensions(${ ComposedComponent.displayName || ComposedComponent.name })`
...
}
I think this is related to:
Basically, I'm using 1.3.0 and its working perfectly:
Dimensions()(FormContent)
but I have the warning:
Wrapper div has no height or width
which I based on github issues 2.0.0 was supposed to solve.
But now I have the problem that pretty much all my styling is 100% messed up and I'm not sure why. 1.3.0 didn't mess with my styling at all and thats what I expect from a HOC.
Can you document how to use this 2.0.0 version without having styles messed up? Right now I see it basically adds this container div with inline styles:
overflow: visible;height: 0px;width: 0px;
but those are really bad styles to be applying to a container div :)
Hello,
I think I might be missing something. It doesn't seem to render my component until the first resize event. Although I cloned the repository and ran the demo - which worked. My code is very similar to the demo, however it's much more complex (as you'd expect :P) I've attached two screen shots.
Before:
https://www.dropbox.com/s/q50gfoh03jt90cw/Screen%20Shot%202016-01-28%20at%205.12.35%20PM.png?dl=0
After:
https://www.dropbox.com/s/dj180ql5hpx1pue/Screen%20Shot%202016-01-28%20at%205.13.00%20PM.png?dl=0
The parent element is rendered in a loop above it. The loop renders an array of dynamic components (it's a survey wizard, data driven so you can re arrange components) but for testing purposes I even hardcoded style={ width: 300px, height: 300px } to the parent to no avail.You see
<div className="question" style=" width: 300px, height: 300px" />
and even your boiler plate css of width and height 100%... just no children until the resize.
What am I doing wrong? Thanks!
If I have a simple child component, with a shallow child tree, then the resize works great
If I have a bigger child component, with a deep child tree, then the browser (IE) starts to lock up when resizing the window, too many resize events are coming through, causing lots of incremental containerWidth changes.
Would it be beneficial to have a configuration setting to debounce the resize event?
this.rqf = window.requestAnimationFrame(() => {
this.rqf = null
this.updateDimensions()
})
Maybe something like this:
http://www.paulirish.com/2009/throttled-smartresize-jquery-event-handler/
I use ant-desing layout
...
render() {
console.log(this.props.containerWidth); // 1506 (work fine)
console.log(this.props.containerHeight); // get 0 (zero)
Some browsers visiting my site do not seem to support requestAnimationFrame - e.g. an extremely outdated Chrome 23. While I do not really want to support these browsers it should be easy enough to just manually execute the wrapped function if window.requestAnimationFrame
is undefined.
On initial render I am getting the window size - if I resize the window I then get the component size but the initial values are wrong.
Any ideas?
Cheers
Rob
When I add the react-dimensions decorator to my Component, it causes an inst.render is not a fuction
error. It works fine otherwise.
The update to babel 6 caused CommonJS require('react-dimensions')
to not work as expected, since the export is now require('react-dimensions').default
- see this article for more info.
For any continued discussion on facebookarchive/fixed-data-table#62
I need to be able to modify the containerStyle when the state changes. Specifically, I have a left-side menu that should slide in/out when the "showMenu" state property is toggled. Is there currently a way to do this?
Hi,
Like the react-redux connect() enhancer, I think react-dimensions should hoist all non-react statics properties to ensure enhancers composability.
Would you like a pull request for this ?
Take a look at https://github.com/mridgway/hoist-non-react-statics
I've made a npm module for simplify this : https://www.npmjs.com/package/react-hoc
I am seeing something odd where when I resize my window the children are disappearing. I am using the react dev tools for chrome and I can see that they are no longer mounted. Once I remove the Dimensions container everything works as expected. Ever seen this before?
Hello,
in my component i just need to calculate height so I change getDimensions to
getDimensions: (element) => { return ['auto' ,element.clientHeight] }.
Afterwards height is calculated correctly, but my element is not visible because its ancestor has width set to 0 and for some reason overflow: visible is not helping.
I changed wrapperStyle from:
var wrapperStyle = {
overflow: 'visible',
height: 0,
width: 0
};
to:
var wrapperStyle = {
height: 'auto',
width: 'auto'
};
and it works nicely afterwards.
Are you planning on adding possibility to change wrapperStyle?
Thanks for great work.
Ferdinand
Having an option to debounce this would be useful; resizes by rotating a mobile device are fine, but dragging to resize on desktop triggers a large number of prop changes.
I am trying to resize the right panel once the left panel is hidden by using {elementResize: true}
. This works fine on PC but not on MAC. The left and right panels are flex items. When the left panel is hidden, i noticed that the dimensions 'div' wrapper is expanding properly but it is not passing the new width to the child. Any ideas?
I've just found this and I am trying to use it. I am having the same problem as @jdelafon in issue #1 . I wrapped my component with Dimensions()(MyComponent) and all I see is a "0" rendered instead of MyComponent. The parent component has width specified and I can access this.props.containerWidth in MyComponent's render() method, but I don't understand why I am getting a "0" div. If manually resize the browser window, then I can see MyComponent rendered normally. Am I missing something? Should I add code to force a resize event?!
Hi, i try to use react dimensions with redux but got an error:
vendor.js:151117 Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
Check the render method of
DimensionsHOC
.
in ConnectFunction (created by DimensionsHOC)
in div (created by DimensionsHOC)
in DimensionsHOC
in Provider
My versions:
"react-dimensions": "^1.3.0",
"react": "^16.8.6",
"redux": "^4.0.1",
My code:
....
import Dimensions from 'react-dimensions';
....
export default Dimensions({
getHeight: function(element) {
return window.innerHeight - 200;
},
getWidth: function(element) {
let widthOffset = window.innerWidth < 1280 ? 70 : 55;
return window.innerWidth - widthOffset;
}
})(connect(mapStateToProps, mapDispatchToProps)(MyComponent));
Would you please update the npm package so we can get rid of the ugly React findDOMNode warnings? :)
Looking at getWrappedInstance method on 1.3.0 and 1.3.1, i see the following:
getWrappedInstance () { this.refs.wrappedInstance }
https://github.com/digidem/react-dimensions/blob/v1.3.1/index.jsx#L149
It's missing return
A LICENSE file is missing in this repository. The package.json says it's MIT.
looks like 1.0.0 is not on npm
edit: nevermind, npm install just defaults to the old version.
I was wondering whether it would be possible to optimally track other events that cause the parent container to recalculate it's dimensions? For instance, if a flexbox sibling suddenly becomes greedier, the parent container will resize, but the window dimensions are still the same.
Running the README generator, npm run doc
, results in a mangled README on master (as of bf4171b):
diff --git a/README.md b/README.md
index 0dda5a2..2475eda 100644
--- a/README.md
+++ b/README.md
@@ -18,7 +18,7 @@ $ npm install react-dimensions
## API
-### Dimensions([options])(MyComponent)
+### index
Wraps a react component and adds properties `containerHeight` and
`containerWidth`. Useful for responsive design. Properties update on
@@ -32,17 +32,24 @@ or as an [ES7 class decorator](https://github.com/wycats/javascript-decorators)
**Parameters**
-- `options` **[object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)=**
- - `options.getHeight` **[function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)=** A function that is passed an element and returns element
- height, where element is the wrapper div. Defaults to `(element) => element.clientHeight`
- - `options.getWidth` **[function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)=** A function that is passed an element and returns element
+- `options` **\[[object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)]**
+ - `options.getWidth` **\[[function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)]** A function that is passed an element and returns element
width, where element is the wrapper div. Defaults to `(element) => element.clientWidth`
- - `options.containerStyle` **[object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)=** A style object for the `<div>` that will wrap your component.
- If you are using a flexbox layout you will need to style this `div` rather than your wrapped component (because flexbox only works with direct children). The default style is
- `{ margin: 0, padding: 0, border: 0 }`.
- - `options.className` **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)=** Control the class name set on the wrapper `<div>`
- - `options.elementResize` **[boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)=** Set true to watch the wrapper `div` for changes in
+ - `options.containerStyle` **\[[object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)]** A style object for the `<div>` that will wrap your component.
+ The dimensions of this `div` are what are passed as props to your component. The default style is
+ `{ width: '100%', height: '100%', padding: 0, border: 0 }` which will cause the `div` to fill its
+ parent in most cases. If you are using a flexbox layout you will want to change this default style.
+ - `options.className` **\[[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)]** Control the class name set on the wrapper `<div>`
+ - `options.elementResize` **\[[boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)]** Set true to watch the wrapper `div` for changes in
size which are not a result of window resizing - e.g. changes to the flexbox and other layout. (optional, default `false`)
+ - `options.getHeight` **\[[function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)]** A function that is passed an element and returns element
+ height, where element is the wrapper div. Defaults to `(element) => element.clientHeight`
+- `$0` **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)** (optional, default `{}`)
+ - `$0.getHeight` (optional, default `defaultGetHeight`)
+ - `$0.getWidth` (optional, default `defaultGetWidth`)
+ - `$0.containerStyle` (optional, default `defaultContainerStyle`)
+ - `$0.className` (optional, default `null`)
+ - `$0.elementResize` (optional, default `false`)
**Examples**
@@ -85,14 +92,6 @@ module.exports = Dimensions()(MyComponent) // Enhanced component
Returns **[function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)** A higher-order component that can be
used to enhance a react component `Dimensions()(MyComponent)`
-### getWrappedInstance()
-
-Returns the underlying wrapped component instance.
-Useful if you need to access a method or property of the component
-passed to react-dimensions. Does not currently work for stateless function components see [#30](https://github.com/digidem/react-dimensions/issues/30)
-
-Returns **[object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)** The wrapped React component instance
-
## Live Example
Will open a browser window for localhost:9966
This module is using the console
API: https://github.com/digidem/react-dimensions/blob/master/index.jsx#L162.
Notice that this API isn't available in IE9. Besides, I don't think that throwing a warning in production has much value.
We could be using https://www.npmjs.com/package/warning with https://www.npmjs.com/package/babel-plugin-transform-dev-warning to remove those check in production.
It would be great if we could pass in options to rename containerWidth
and containerHeight
to other things. Some components expect width
and height
directly, and right now I have to add yet another a wrapper component to rename the props (e.g., width={this.containerWidth} height={this.containerHeight}
).
I suppose another option would be to have a higher order component whose only job is to rename props (just found recompose.renameProps()
: https://github.com/acdlite/recompose/blob/master/docs/API.md#renameprops), but that adds some overhead.
I can work on a PR if this is something you'd like to add.
I'm a little confused on how to write enzyme tests for a component that uses react-dimensions
The component looks like this:
const Show = React.createClass({
// shortened for brevity.
render () {
var width = 0.4 * this.props.containerWidth,
height = width,
radius = 0.5 * width
return (
<div>
<h1>{this.state.poll.name}</h1>
<div className="container-fluid">
// lots more stuff removed for brevity
</div>
</div>
)
}
})
export default Dimensions()(Show)
I'm trying to test it like this:
it("contains an h1 as first child", (done) => {
const wrapper = mount(<Show />);
expect(wrapper.find('h1')).to.have.length(1);
done()
});
The above test fails with AssertionError: expected { Object (component, root, ...) } to have a length of 1 but got 0
I looked at the value of wrapper.html()
and get <div style="width: 100%; height: 100%; padding: 0px; border: 0px;">0</div>
. I believe this touches on #28, but as things work just fine in my browser I'm confused as to why it does not behave as I would expect in my tests. Any ideas? Is there any other code I can provide that would shed light on this situation? Thanks.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.