Skip to content

Commit

Permalink
fix: store support for object-fit in ref to prevent slider from alway…
Browse files Browse the repository at this point in the history
…s using fallback in SSR scenarios
  • Loading branch information
nerdyman committed Apr 5, 2020
1 parent 96a3c1a commit f0352ac
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 13 deletions.
3 changes: 1 addition & 2 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,8 @@ export {
} from './react-compare-slider';

export {
CLIENT_SUPPORTS_CSS_OBJECT_FIT,
ReactCompareSliderImage,
ReactCompareSliderImageProps,
} from './react-compare-slider-image';

export { styleFitContainer } from './utils';
export { styleFitContainer, supportsCssObjectFit } from './utils';
16 changes: 5 additions & 11 deletions src/react-compare-slider-image.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,6 @@
import React from 'react';
import React, { useRef } from 'react';

import { styleFitContainer } from './utils';

/**
* Whether client supports the CSS `object-fit` property.
*/
export const CLIENT_SUPPORTS_CSS_OBJECT_FIT: boolean =
typeof CSS !== 'undefined' &&
CSS.supports &&
CSS.supports('object-fit', 'cover');
import { styleFitContainer, supportsCssObjectFit } from './utils';

/**
* Properties for `ReactCompareSliderImage`.
Expand All @@ -31,14 +23,16 @@ export const ReactCompareSliderImage: React.FC<React.ImgHTMLAttributes<
style,
...props
}): React.ReactElement => {
/** Runtime support for `object-fit`. Ref based to allow updates after SSR. */
const objectFitIsSupported = useRef(supportsCssObjectFit());
const innerStyle: React.CSSProperties = styleFitContainer({ ...style });
const containerStyle: React.CSSProperties = {
width: innerStyle.width,
height: innerStyle.height,
};

// Add fallback background props if requested
if (!CLIENT_SUPPORTS_CSS_OBJECT_FIT && fallbackEnable) {
if (!objectFitIsSupported && fallbackEnable) {
// Set fallback CSS properties, use props from `innerStyle` if defined
containerStyle.backgroundImage =
innerStyle.backgroundImage || `url(${props.src})`;
Expand Down
8 changes: 8 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,14 @@ import {
import { ResizeObserver } from 'resize-observer';
import { ContentRect } from 'resize-observer/lib/ContentRect';

/**
* Whether client supports the CSS `object-fit` property.
*/
export const supportsCssObjectFit = (): boolean =>
typeof CSS !== 'undefined' &&
CSS.supports &&
CSS.supports('object-fit', 'cover');

/**
* Stand-alone CSS utility to make replaced elements (`img`, `video`, etc.)
* fit their container and maintain their aspect ratio.
Expand Down

0 comments on commit f0352ac

Please sign in to comment.