Skip to content

Commit

Permalink
Automatically set srcSet attributes
Browse files Browse the repository at this point in the history
This adds a new option called `srcSet` which defaults to true. When enabled, the 2x and 3x srcSet attributes will be added to rendered component. Currently, the attribute will only be added if the rendered component is an `img`.
  • Loading branch information
ekosz committed Nov 17, 2015
1 parent 214de97 commit faa1f11
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
22 changes: 18 additions & 4 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ export default class ReactImgix extends Component {
fluid: PropTypes.bool,
children: PropTypes.any,
customParams: PropTypes.object,
entropy: PropTypes.bool
entropy: PropTypes.bool,
srcSet: PropTypes.bool
}
static defaultProps = {
precision: 100,
Expand All @@ -45,7 +46,8 @@ export default class ReactImgix extends Component {
faces: true,
fit: 'crop',
entropy: false,
auto: ['format']
auto: ['format'],
srcSet: true
}
state = {
width: null,
Expand All @@ -64,6 +66,7 @@ export default class ReactImgix extends Component {

render () {
let src = ''
let srcSet = ''
let component = this.props.component

let width = this._findSizeForDimension('width')
Expand All @@ -78,14 +81,19 @@ export default class ReactImgix extends Component {
if (this.props.fit) fit = this.props.fit

if (this.state.mounted || this.props.aggresiveLoad) {
src = processImage(this.props.src, {
const srcOptions = {
auto: this.props.auto,
...this.props.customParams,
crop,
fit,
width,
height
})
}

src = processImage(this.props.src, srcOptions)
const dpr2 = processImage(this.props.src, {...srcOptions, dpr: 2})
const dpr3 = processImage(this.props.src, {...srcOptions, dpr: 3})
srcSet = `${dpr2} 2x, ${dpr3} 3x`
}

let childProps = {...this.props}
Expand All @@ -100,10 +108,16 @@ export default class ReactImgix extends Component {
backgroundSize: 'cover'
}
delete childProps.src
delete childProps.srcSet
} else {
if (!this.props.component) {
component = 'img'
}

if (component === 'img' && this.props.srcSet) {
childProps.srcSet = srcSet
}

childProps.src = src
}
return React.createElement(component,
Expand Down
13 changes: 13 additions & 0 deletions src/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -118,4 +118,17 @@ describe('image props', () => {
// it.skip('custom props', () => {
// expect(vdom.props.src).to.include('auto=format,enhance')
// })
it('srcSet prop', () => {
tree = sd.shallowRender(
<Imgix
src={src}
aggresiveLoad
srcSet
/>
)
vdom = tree.getRenderOutput()

expect(vdom.props.srcSet).toInclude('dpr=2')
expect(vdom.props.srcSet).toInclude('dpr=3')
})
})

0 comments on commit faa1f11

Please sign in to comment.