jumpo marketing
jumpo marketing

Reputation: 697

How can I change state in client-side in NEXT.js?

I have a simple tab component in NEXT. Here's my component code:

const Tabs = ({ tabItems }) => {

    const setActiveTab = (tabItem) => {
        for (var i = 0; i < tabItems.length; i++) {
            tabItems[i].active = false;
        }
        tabItem.active = true;
    }

    return <div>
        {
            tabItems.map(tabItem => <div
                className={tabItem.active ? "active-tab" : ""}
                onClick={() => setActiveTab(tabItem)}
            >{tabItem.title}</div>)
        }
    </div>
}

However, when I click on tab items, the state does not change.

How can I change state in client-side in NEXT?

Upvotes: 0

Views: 581

Answers (1)

Gustavo Farias
Gustavo Farias

Reputation: 423

You can't change state from a parent like this. The way that you're doing, you're only changing the value of tabItem inside the children component.

You could use Context API to achieve the desired result, or just pass down a function from the parent, which would be the best if you're not passing props down too many components.

Code example:

parent.tsx:

export const Parent = () => {
  const [tabItems, setTabItems] = useState()

  function changeTabItems(newValue) {
    setTabItems(newValue)
  }

  return <Child changeTabItems={changeTabItems} tabItems={tabItems}/>
}

child.tsx:

export const Child = ({changeTabItems, tabItems}) => {
  function setActiveTab(tabItem) {
    let aux = tabItems
    for (var i = 0; i < tabItems.length; i++) {
      aux[i].active = false;
    }
    aux.active = true;
    changeTabItems({...aux})
  }

}

Upvotes: 1

Related Questions