s_kov
s_kov

Reputation: 3

How can I make first element className active when page loads?

I have pagination and it changes style of element on click by changing a className to 'active'. Is there any way to have className='active' on first link by default when page loads until you click on another page? Here's what I have now:

function Pagination({postsPerPage, totalPosts, paginate}) {
    const pageNumbers = [];
    const [active, setActive] = useState('');

    for (let i = 1; i <= Math.ceil(totalPosts / postsPerPage); i++) {
        pageNumbers.push(i);
    }

    return(
        <div className='pagination'>
            {pageNumbers.map(number => (
                <a
                    className={active === number ? 'active' : ''}
                    key={number}
                    onClick={() => {
                        paginate(number);
                        setActive(number);
                    }}
                    href="#">{number}
                </a>
            ))}
        </div>
    );
}

Upvotes: 0

Views: 38

Answers (1)

dave
dave

Reputation: 64715

Just set the initial state to 1:

const [active, setActive] = useState(1);

Upvotes: 2

Related Questions