I am trying to create a reusable carousel, where carousel items are scrollable and clickable. Carousel item can be any component which is passed as children to Carousel. The problem is that when I try to pass selected state as prop in the child component using React.cloneElement I get this error react docs Unknown prop warning. There are several answers in stack overflow like this that inspired my solutionand this that exposes the problembut with no good answers specific to my situation. My code so far is this:
import React, { useState } from 'react';
import CarouselItem from './CarouselItem';
type Props = {
children: Array<React.FC>;
};
const Carousel: React.FC<Props> = ({ children }: Props) => {
const [selected, setSelected] = useState(0);
const handleSelect: (index: number) => void = (index: number) => {
setSelected(index);
};
console.log('children', children);
return (
<div className="flex w-full items-center justify-start overflow-y-scroll">
{children.map((child, index) => (
<CarouselItem
key={`carousel-item${index + 1}`}
selected={selected}
index={index}
child={child}
handleSelect={handleSelect}
/>
))}
</div>
);
};
export default Carousel;
import Link from 'next/link';
import React, { useState, useEffect, createContext } from 'react';
interface Props {
selected: number;
index: number;
child: JSX.Element;
handleSelect: (index: number) => void;
}
const CarouselItem: React.FC<Props> = (props) => {
const a = 1;
// props.child.props.children.props.isSelected = 'true';
console.log('typeof props.child', typeof props.child.type);
return (
<li
onClick={() => props.handleSelect(props.index)}
className={`${
props.selected == props.index ? 'selected' : 'unselected'
} list-none`}
>
{React.cloneElement(props.child, {
isSelected: 'true'
})}
</li>
);
};
export default CarouselItem;
const LiveSport: NextPage = () => {
console.log();
return (
<>
<div className="hidden">
<SportsSvgIcons />
</div>
<Carousel>
{carouselMockData.map((itemData, index) => (
<div key={`sport-carousel-${index + 1}`}>
<CarouselSportItem {...itemData} />
</div>
))}
</Carousel>
</>
);
};
export default LiveSport;
The error comes from here:
const CarouselSportItem: React.FC<CarouselSportItemData> = (props) => {
console.log('props', props);
const divProps = Object.assign({}, props);
delete divProps.isSelected;
return (
<div
className={``}
>
<Link href={`${props.sportCode}`}>
<div>
<div>
<div>{`${props.name}`}</div>
</div>
<div>
<div>
{props.isSelected}
</div>
</div>
</div>
</Link>
</div>
);
};
export default CarouselSportItem;
props.isSelected is not there, and I get this error message:
Warning: React does not recognize the
isSelectedprop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercaseisselectedinstead. If you accidentally passed it from a parent component, remove it from the DOM element.