'How to use useRef in React
I have a sidebar with filters, several filters displayd on home page for example 'price', 'actions'.. it is a tag component
<Tag
key={filter.fieldCode}
text={filter.displayName}
icon={<IconCross />}
type="soft"
size={"md"}
onClick={
() => goToFilters(filter.displayName)
}
/>
then in the method goToFilters I toggle another component multyFilter and set name of category filter fox example 'Price'
const [namef, setNamef] = useState("");
const goToFilters = (name) => {
setNamef(name);
handleToggleFilter(name);
};
then if multyFilter is true I display MultyFilter component
{multyFilter && (
<MultyFilter
setMultyFilter={handleToggleFilter}
filters={filters}
handleToggleFilter={handleToggleFilter}
name={namef}
/>
)}
in the MultyFilter I have a FilterBox component
<FilterBox entry={entry} type={entry.type}/>
FilterBox - component for each filter, for price or actions.
in the FilterBox I have a switch case for selectig what type of filter will be dislpayed
switch (type) {
case 1:
return (
<div className={style.filterBox}>
<div className={style.title}>{entry.displayName}</div>
{showAll
? visibleProps.map((prop) => (
<>
<label className={`${style.check} ${style.option}`}>
<input
type="checkbox"
onChange={(e) => handleClick(e)}
className={style.check__input}
/>
<span className={style.check__box}></span>
<span className={style.name}>{prop.displayName}</span>
</label>
</>
))
: visibleProps.slice(0, 5).map((prop) => (
<>
<label className={`${style.check} ${style.option}`}>
<input type="checkbox" className={style.check__input} />
<span className={style.check__box}></span>
<span className={style.name}>{prop.displayName}</span>
</label>
</>
))}
{!showAll && visibleProps.length > 5 ? (
<button
onClick={() => handleShowAll(entry.id)}
className={style.showAllBtn}
>
Показать все
</button>
) : visibleProps.length > 5 ? (
<button
onClick={() => handlHideAll(entry.id)}
className={style.hideAllBtn}
>
Скрыть
</button>
) : null}
</div>
);
break;
case 2:
return <></>;
break;
case 3:
return (
<>
<RangeFilterBox name={entry.displayName} id={entry.id} filters={entry.properties} />
</>
);
break;
When I tap on button with name price, my filter sidebar is opening and I want to scroll on field with name price, to scroll to selected filter, how to do it i don't know. I thought about ref
const elementRef = useRef(null);
useEffect(() => {
elementRef.current.scrollIntoView();
}, []);
<FilterBox entry={entry} type={entry.type} ref={elementRef} />
But How to define what exactly filter I need I have a name of filter in component MultyFilter
<MultyFilter
name={namef}
/>
but how to use it, i don't know, help me if u know how to do it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
