C-B
C-B

Reputation: 33

Get Value clicked in material-ui \ core \ Slider

Development - react.

Task:

Display a line with dots that mark percentages between 0 and 100.

The data comes outside the component (for the purpose of the example I created a static array).

The quantity and value of the values is dynamic.

The task is required to click on a point, for which purpose it is necessary to know at which point in the click event which clicked.

The solution I tried:

Using material-ui \ core \ Slider.

I disabled the ability of the slide so that the points remain static by updating the value each time in the original values.

The only event that exists in Slider is onChange it happens when you click anywhere on Slider. But the event does not return the location where you clicked but the new values it wants to calculate. And by clicking on one of the points the values simply remain as they are unchanged.

My code:

import React from 'react';
import { Slider, Tooltip } from '@material-ui/core';

export default function App() {
  
  const marks = [
    { value: 0, label: '0%' },
    { value: 100, label: '100%' },
  ];
  
  const ValueLabelComponent = (props) => {
    const { children, open, value } = props;
      return (
          <Tooltip open={open} enterTouchDelay={0} placement="bottom" title={`${value}%`}>
            {children}
          </Tooltip>
      );
  }

  return (
    <div className='container'>
      <Slider
        value={[ 0, 5, 70, 88, 93]}
        ValueLabelComponent={ValueLabelComponent}
        track={false}
        onChange={(event, value) => { console.log(event, value) }}
        marks={marks}
      />
    </div>
  );
}

My questions are:

  1. Does anyone have any idea how to get the value of the pressed point?

  2. Or alternatively whether there is a solution in the use of another component.

Upvotes: 1

Views: 1388

Answers (1)

Jake
Jake

Reputation: 4255

Try this:

import React from 'react';
import { Slider, Tooltip } from '@material-ui/core';

export default function App() {
  
  const marks = [
    // Save the fetched values here instead of under <Slider value=...>
    { value: 0, label: '0%' },
    { value: 5, label: '5%' },
    { value: 70, label: '70%' },
    { value: 88, label: '88%' },
    { value: 93, label: '93%' },
    { value: 100, label: '100%' },
  ];
  
  const ValueLabelComponent = (props) => {
    const { children, open, value } = props;
      return (
          <Tooltip open={open} enterTouchDelay={0} placement="bottom" title={`${value}%`}>
            {children}
          </Tooltip>
      );
  }

  return (
    <div className='container'>
      <Slider
        ValueLabelComponent={ValueLabelComponent}
        track={false}
        onChange={(event, value) => console.log(`Value of ${value} clicked`) }
        marks={marks}
        steps={null}
      />
    </div>
  );
}

Upvotes: 1

Related Questions