Skip to content

Commit a5e7b9f

Browse files
authored
Add rem example (#480) (#487)
1 parent 9c5e8c3 commit a5e7b9f

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

example/example.js

+50
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,16 @@ class App extends React.Component {
141141
I already have an absolute position.
142142
</div>
143143
</Draggable>
144+
<Draggable {...dragHandlers}>
145+
<RemWrapper>
146+
<div className="box rem-position-fix" style={{position: 'absolute', bottom: '6.25rem', right: '18rem'}}>
147+
I use <span style={{ fontWeight: 700 }}>rem</span> instead of <span style={{ fontWeight: 700 }}>px</span> for my transforms. I also have absolute positioning.
148+
149+
<br /><br />
150+
I depend on a CSS hack to avoid double absolute positioning.
151+
</div>
152+
</RemWrapper>
153+
</Draggable>
144154
<Draggable defaultPosition={{x: 25, y: 25}} {...dragHandlers}>
145155
<div className="box">
146156
{"I have a default position of {x: 25, y: 25}, so I'm slightly offset."}
@@ -181,4 +191,44 @@ class App extends React.Component {
181191
}
182192
}
183193

194+
class RemWrapper extends React.Component {
195+
// PropTypes is not available in this environment, but here they are.
196+
// static propTypes = {
197+
// style: PropTypes.shape({
198+
// transform: PropTypes.string.isRequired
199+
// }),
200+
// children: PropTypes.node.isRequired,
201+
// remBaseline: PropTypes.number,
202+
// }
203+
204+
translateTransformToRem(transform, remBaseline = 16) {
205+
const convertedValues = transform.replace('translate(', '').replace(')', '')
206+
.split(',')
207+
.map(px => px.replace('px', ''))
208+
.map(px => parseInt(px, 10) / remBaseline)
209+
.map(x => `${x}rem`)
210+
const [x, y] = convertedValues
211+
212+
return `translate(${x}, ${y})`
213+
}
214+
215+
render() {
216+
const { children, remBaseline = 16, style } = this.props
217+
const child = React.Children.only(children)
218+
219+
const editedStyle = {
220+
...child.props.style,
221+
...style,
222+
transform: this.translateTransformToRem(style.transform, remBaseline),
223+
}
224+
225+
return React.cloneElement(child, {
226+
...child.props,
227+
...this.props,
228+
style: editedStyle
229+
})
230+
}
231+
}
232+
233+
184234
ReactDOM.render(<App/>, document.getElementById('container'));

example/index.html

+10
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,16 @@
5151
padding: 10px;
5252
float: left;
5353
}
54+
55+
56+
/*
57+
* RemWrapper needs to take it's styles from this element,
58+
* and this element can't have an absolute position after it's kicked in.
59+
* AFAIK it's not possible to do this directly in the RemWrapper component.
60+
*/
61+
.rem-position-fix {
62+
position: static !important;
63+
}
5464
</style>
5565
</head>
5666
<body>

0 commit comments

Comments
 (0)