Material UI Rating wrapping long values

Viewed 104

I am currently trying to work around the Material UI rating component and how to do a flex-wrap if the icons overflow the width of the parent component.

If I try to add flex-wrap: wrap to the rating component, it actually wraps the icons but the interactive functionality stops working pas the first line.

Here is a code example below to better demonstrate this:

Code Example in CodeSandbox

Is there a way to make it work with flex-wrap? If anyone could help I will very much appreciate.

1 Answers

I have decided that was better to build one by myself with the ability to wrap if the max value is big.

Will leave it here so someone who might have the same issue as me can use it.

CustomRating.js

import React, { useState } from 'react'
import { Tooltip } from '@mui/material'
import './CustomRating.css'

function CustomRating({ max, value, onChange, icon, emptyIcon }) {
    const [innerValue, setInnerValue] = useState(value)

    const checkIfIconInsideValue = (index) => {
        return value >= index + 1
    }

    const handleMouseHover = (e, index) => {
        if (e.type === 'mouseenter') {
            setInnerValue(index)
            return
        }
        setInnerValue(value - 1)
    }

    return (
        <Tooltip title={innerValue} placement='top'>
            <div className='custom-rating-main-div'>
                {Array.from({ length: max }).map((elem, index) => {
                    return (
                        <div
                            className={`custom-rating-icon-div ${checkIfIconInsideValue(index) ? 'filled' : ''}`}
                            key={index}
                            onClick={() => onChange(index + 1)}
                            onMouseEnter={(e) => handleMouseHover(e, index)}
                            onMouseLeave={(e) => handleMouseHover(e, index)}
                        >
                            {checkIfIconInsideValue(index) || innerValue >= index ? icon : emptyIcon}
                        </div>
                    )
                })}
            </div>
        </Tooltip>
    )
}

export default CustomRating

CustomRating.css

.custom-rating-main-div {
    display: flex;
    flex-wrap: wrap;
}

.custom-rating-icon-div {
    cursor: pointer;
}

.custom-rating-icon-div.filled > svg {
    fill: #61634f
}

.custom-rating-icon-div > svg {
    fill: rgba(97, 99, 79, 0.5)
}

.custom-rating-icon-div:hover > svg {
    fill: #61634f;
    transform: scale(1.2);
}

As you may notice this is specific to my problem but can be very easily adapted to any case.

keep in mind that this is very rough and can be updated to better follow conventions and for better performance, but for now it is my solution

Related