David R
David R

Reputation: 193

Add toggle class to div in React

I want to expand on this example where I click on the "Show more" button and it scrolls to the div, I would like to add a toggle class to the show more component.

import React, { useRef } from 'react'

const Article = () => {
    const titleRef = useRef()

    function handClick() {

       // Add toggle class for show-more???

       titleRef.current.scrollIntoView({ behavior: 'smooth' })
    }

    return (
        <article>
            <button onClick={handClick}>Show more</button>
            <div className="show-more" ref={titleRef}>Some content to show onclick</div>
        </article>
    )
}

Upvotes: 2

Views: 935

Answers (1)

helrabelo
helrabelo

Reputation: 551

Try:

import React, { useRef, useState } from 'react'

const Article = () => {
    const titleRef = useRef()
    
    const [showMore, setShowMore] = useState(false);

    function handClick() {

       setShowMore(!showMore);

       titleRef.current.scrollIntoView({ behavior: 'smooth' })
    }

    return (
        <article>
            <button onClick={handClick}>Show more</button>
            <div className=`show-more ${showMore ? 'showMoreClass' : ''}` ref={titleRef}>Some content to show onclick</div>
        </article>
    )
}

Upvotes: 2

Related Questions