tajo / react-range

🎚️Range input with a slider. Accessible. Bring your own styles and markup.
https://react-range.pages.dev
MIT License
859 stars 97 forks source link

Marks do not correctly re-render on state change #183

Open johnlahut opened 2 years ago

johnlahut commented 2 years ago

Having trouble dynamically updating marks on the line. My goal is to conditionally render marks on a timeline. Our domain is around a year, with each step representing a minute.

After updating the marks state variable, the renderMark function does not seem to correctly render.

If I resize the parent container, the component updates and the marks suddenly appear.

import { Thumb } from "./components/Thumb"
import { Track } from "./components/Track"

export const Timeline = ({
  min,
  max,
  step,
  initialValues
}: {
  min?: number,
  max?: number,
  step?: number,
  initialValues?: number[],
}) => {

  const [values, setValues] = useState<number[]>(initialValues ?? [MAX_TIME])
  const [marks, setMarks] = useState<number[]>([]);

  return (
    <div style={{
      padding: '20px',
      display: 'flex',
      justifyContent: 'center',
      flexWrap: 'wrap'
    }}>

      <Range
        min={min ?? MIN_TIME}
        max={max ?? MAX_TIME}
        step={step ?? STEP}
        values={values}
        onChange={(values: number[]) => setValues(values)}
        renderMark={({ props, index }) => {
          if (marks.includes(index)) {
            return (
              <div
                {...props}
                style={{
                  ...props.style,
                  height: '15px',

                  width: '5px',
                  backgroundColor: 'gray',
                }} />
            )
          }

          else {
            return undefined;
          }
        }}
      renderThumb={Thumb}
      renderTrack={Track} />

      <div>
        {values[0]}
      </div>

      <button onClick={() => setMarks([100, 200, 300])}>
        Set Marks
      </button>
    </div>
  )
}
michaelmota commented 1 year ago

Any updates on this?

tarikyildizci commented 11 months ago
<Range
  ref={(e) => {
    e?.calculateMarkOffsets()
  }}
/>

This is a workaround that worked for me, sometimes the lib cannot calculate correct offsets for some reason.