I
I
IIITRIX2020-06-04 17:00:19
React
IIITRIX, 2020-06-04 17:00:19

How to properly use useState?

Can you please tell me how to use useState correctly?
In my case, I need the currentLinkLabel to change depending on the pathname from initialState

import { useState } from 'react'
import { useRouter } from 'next/router'
import Link from 'next/link'

const initialState = [
  { label: 'Книги', pathname: '/' },
  { label: 'Альбомы', pathname: '/album' },
  { label: 'Разное', pathname: '/other' },
]

export default function Navigation() {
  const router = useRouter()
  const [links, setLinks] = useState(initialState)
  const [currentLink, setCurrentLink] = useState('/')
  const changeCurrentLink = pathname => {
    const setCurrentLink = links.find(el => el.pathname === pathname).pathname
  }
  const dropdownLinks =
    router.pathname !== '/' &&
    router.pathname !== '/new'
      ? links.filter(el => el.pathname !== currentLink)
      : links.filter(el => el.pathname !== '/')
  const currentLinkLabel =
    router.pathname !== '/' &&
    router.pathname !== '/new'
      ? links.find(el => el.pathname === currentLink).label
      : 'Книги'
  const currentLinkPathname =
    router.pathname !== '/' &&
    router.pathname !== '/new'
      ? links.find(el => el.pathname === currentLink).pathname
      : '/'
  return (
    <div className='container'>
      <a className='link' href={currentLinkPathname}>
         {currentLinkLabel}
      </a>
       {dropdownLinks.map((link, index) => {
          return (
          <React.Fragment key={index}>
              <Link href={link.pathname}>
                  <a className='item' onClick={changeCurrentLink(link.pathname)}>
                      {link.label}
                  </a>
              </Link>
          </React.Fragment>
          )
       })}
    </div>
  )
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question