Skip to content

Commit 2e77572

Browse files
nirmaozNir Maoz
authored andcommitted
Add support for innerRef to the Image component
1 parent 08e62a9 commit 2e77572

File tree

2 files changed

+34
-7
lines changed

2 files changed

+34
-7
lines changed

src/components/Image/Image.js

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,10 @@ class Image extends CloudinaryComponent {
1414
constructor(props, context) {
1515
super(props, context);
1616
this.handleResize = this.handleResize.bind(this);
17-
18-
this.state = {};
17+
this.attachRef = this.attachRef.bind(this);
1918

2019
let state = {responsive: false, url: undefined, breakpoints: defaultBreakpoints};
21-
this.state = Object.assign(state, this.prepareState(props, context));
20+
this.state = {...state, ...this.prepareState(props, context)};
2221
}
2322

2423
/**
@@ -60,6 +59,19 @@ class Image extends CloudinaryComponent {
6059
return state;
6160
}
6261

62+
attachRef(element) {
63+
this.element = element;
64+
const {innerRef} = this.props;
65+
66+
if (innerRef) {
67+
if (innerRef instanceof Function) {
68+
innerRef(element);
69+
} else {
70+
innerRef.current = element;
71+
}
72+
}
73+
}
74+
6375
handleResize() {
6476
if (!this.props.responsive || this.rqf) return;
6577
this.rqf = requestAnimationFrame(() => {
@@ -98,14 +110,12 @@ class Image extends CloudinaryComponent {
98110
}
99111

100112
render() {
101-
const {publicId, responsive, responsiveDebounce, children, ...options} =
113+
const {publicId, responsive, responsiveDebounce, children, innerRef, ...options} =
102114
CloudinaryComponent.normalizeOptions(this.props, this.getContext());
103115
const attributes = cloudinary.Transformation.new(options).toHtmlAttributes();
104116
const {url} = this.state;
105117
return (
106-
<img {...attributes} src={url} ref={(e) => {
107-
this.element = e;
108-
}}/>
118+
<img {...attributes} src={url} ref={this.attachRef}/>
109119
);
110120
}
111121

test/ImageTest.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,4 +130,21 @@ describe('Image', () => {
130130
tag.setProps({responsive:true});
131131
expect(tag.find('img').prop('src')).to.equal('http://res.cloudinary.com/demo/image/upload/sample');
132132
});
133+
it('Should support forwarding innerRef to underlying image element', function () {
134+
const expected = 'http://res.cloudinary.com/demo/image/upload/sample';
135+
let myRef = React.createRef();
136+
137+
let tag = mount(
138+
<Image
139+
innerRef={myRef}
140+
cloudName='demo'
141+
publicId='sample'
142+
/>
143+
);
144+
145+
const image = myRef.current;
146+
147+
expect(tag.find('img').prop('src')).to.equal(expected);
148+
expect(image.src).to.equal(expected);
149+
});
133150
});

0 commit comments

Comments
 (0)