Home > Back-end >  Show or Hide on div among multiple divs React
Show or Hide on div among multiple divs React

Time:12-25

I was trying to render a component based on the dropdown click.

Here is my code

const App = () => {
    const [showPlayer, setShowPlayer] = useState();

    const switchVisibleDiv = ({divNumber}) => {
        setShowPlayer({showPlayer: divNumber})
    }

    return(
        <>
            <DropdownButton id="dropdown-basic-button" title="Dropdown Menu">
                {data.map((info, index) => (
                    <Dropdown.Item key={index} onClick={() => switchVisibleDiv(index)}>Title - {data.title}</Dropdown.Item>
                ))}
            </DropdownButton>

            {data.map((video, index) => (
            (showPlayer === index ?
                <Plyr
                key={index}
                options={options}
                source={{
                    type: 'video',
                    title: 'Example title',
                    sources: [
                        {
                        `${video.video_url}`,
                        type: 'video/mp4',
                        size: 1080,
                        }
                    ]
                    }}
                />
                : null)
            ))}
        </>
    )
}

But it does not seems to be working i took the reference from an answer from here which was a class component and tried converting that into function component.

Link to answer

CodePudding user response:

You should change this callback function for the DropdownButton component.

const switchVisibleDiv = ({divNumber}) => {
    setShowPlayer(divNumber)
}

It will be working then, the original approach is Class Component format and in Functional Component, we don't use like that, just pass the divNumber as a parameter for the setShowPlayer setter function.

Then it will work.

CodePudding user response:

You need to set a number and not an object :

    const switchVisibleDiv = (divNumber) => {
        setShowPlayer(divNumber})
    }

One more thing you could have done is remove the function and simply set state from here:

<DropdownButton id="dropdown-basic-button" title="Dropdown Menu">
                {data.map((info, index) => (
                    <Dropdown.Item key={index} onClick={() => setShowPlayer(index)}>Title - {data.title}</Dropdown.Item>
                ))}
            </DropdownButton>

PS: Use something else instead of index as key. It is not recommended.

  • Related