Reputation: 5566
I would like to set a background to a certain div using react ref, here is what I have tried so far:
The class component:
import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
export default class CalendarDay extends React.Component {
constructor(props) {
super(props);
this.backgroundImageRef = React.createRef();
}
render () {
let { day, isToday, events, onClick } = this.props;
const dayClasses = classnames({
'flexColumn': true,
'day': true,
'inactive': day.siblingMonth,
'today': isToday,
});
if(typeof day.eventSlots !== 'undefined' && day.eventSlots.length > 0 ) {
let getEventData = Object.values(day.eventSlots)[0].eventClasses;
switch (getEventData) {
case 'event1':
let getInnerGrid = this.backgroundImageRef.current;
console.log(getInnerGrid); // returns null
//event1.style.backgroundImage = "url('../images/eventbg1.svg')";
console.log(getEventData);
break;
default:
break;
}
}
return (
<div
onClick={onClick.bind(null, this, day)}
className={dayClasses}>
<div ref={this.backgroundImageRef} className="inner-grid">
<div className="date">
{day.day}
</div>
{events}
</div>
</div>
);
}
}
CalendarDay.propTypes = {
day: PropTypes.object.isRequired,
isToday: PropTypes.bool,
events: PropTypes.array,
onClick: PropTypes.func,
};
Now when I run the app and check the console, I see the null. What am I doing wrong here?
Upvotes: 0
Views: 1527
Reputation: 8135
You can create a bgStyle
, and update bgStyle based on condition
. Then u can directly use on div
as style prop.
let bgStyle = {}
if(typeof day.eventSlots !== 'undefined' && day.eventSlots.length > 0 ) {
let getEventData = Object.values(day.eventSlots)[0].eventClasses;
switch (getEventData) {
case 'event1':
bgStyle.backgroundImage = "url('../images/eventbg1.svg')"
break;
default:
break;
}
}
return (
<div style={bgStyle} className="inner-grid">
<div className="date">
{day.day}
</div>
{events}
</div>
);
Upvotes: 2