reactjscodesandbox

I can't set the first item as default in listing in react js


I am creating an items listing with categories.

I want to have it such that when user first visits the site, the default first category should be active, but at the moment, all items are appearing.

After clicking on particular category then item results are right.

You can check full codesandbox here.


Solution

  • It's because for the workItems state, you initialize it with useState(workingList) which contains all the items. Meanwhile, the filtering based on the category happens only after a WorkList element is clicked (which call the setWorkItems).

    My advice is to put the active state in the root directly App.js, and remove the workingItems state. Instead, you can make it directly as a variable that is calculated during render. Also, for things that don't change (like categories state here), you don't need to put it inside useState.

    Codesandbox