im just trying to set a Ref to an imported React Icon. But for some reason it does not work. I receive the following error message:
"TypeError: Cannot read properties of undefined (reading 'style')"
Is there a special way to refer to an imported file?
import React from 'react'
import { useRef } from 'react'
import {HiPlus, HiThumbDown, HiThumbUp, HiArrowNarrowRight} from "react-icons/hi"
function Card(props) {
var addToFavRef = useRef()
var thumbUpRef = useRef()
var thumbDownRef = useRef()
function addToFavorites(){
addToFavRef.current.style.color = "orange"
addToFavRef.current.style.transform = "rotate(45deg)"
}
function thumbUp(){
thumbDownRef.current.style.color = "grey"
thumbDownRef.current.style.opacity = "50%"
}
return (
<>
<HiPlus className="cardPlusIcon" ref={addToFavRef}></HiPlus>
<HiThumbUp className="cardThumbUp" ref={thumbUpRef} onClick={thumbUp}></HiThumbUp>
<HiThumbDown className="cardThumbDown" ref={thumbDownRef} onClick={thumpDown}></HiThumbDown>
</>
)
}
export default Card
Here's the message:
I don't believe that there is a ref attached to the react icons svg. If you use typescript you can see the error when you try to add one.
If you really must access the dom node then you can wrap each icon in a div or span and attach a ref to that and then you can access it by the child node like ref.current.childNodes[0]
But it makes no sense in your case to do this if you are going to set the style just set it. There is no reason to access the dom node here. You can do so by adding classes or just setting the style directly.
import {HiPlus, HiThumbDown, HiThumbUp, HiArrowNarrowRight} from "react-icons/hi"
import {useState} from 'react'
const thumbsUpStyle = {
color: 'orange',
transform: 'rotate(45deg)'
}
const thumbsDownStyle = {
color: 'orange',
transform: 'rotate(-45deg)'
}
const favoritesStyle = {
color: 'grey',
opacity: '50%'
}
export default function Card() {
const [thumbs, setThumbs] = useState('')
const [favorites, setFavorites] = useState(false)
return (
<div className="card">
<HiPlus onClick={() => setFavorites(true)} style={favorites && favoritesStyle}/>
<HiThumbUp onClick={() => setThumbs('up')} style={thumbs === 'up' && thumbsUpStyle}/>
<HiThumbDown onClick={() => setThumbs('down')} style={thumbs === 'down' && thumbsDownStyle}/>
</div>
);
}
Or just add a corresponding class and style that class in your stylesheet
import {HiPlus, HiThumbDown, HiThumbUp, HiArrowNarrowRight} from "react-icons/hi"
import {useState} from 'react'
export default function Card() {
const [thumbs, setThumbs] = useState('')
const [favorites, setFavorites] = useState(false)
return (
<div className="card">
<HiPlus onClick={() => setFavorites(true)} className={favorites && 'favorites-class'}/>
<HiThumbUp onClick={() => setThumbs('up')} className={thumbs === 'up' && 'thumbs-up-class'}/>
<HiThumbDown onClick={() => setThumbs('down')} className={thumbs === 'down' && 'thumbs-down-class'}/>
</div>
);
}