CheeseDanish1
CheeseDanish1

Reputation: 13

Dont know why I am getting to many re-render errors

Here is my code

import React, {useState} from 'react';
import Category from './Category.jsx';

function Categories() {
  const [active, setActive] = useState(0);

  let nameArr = [
    'All',
    'Life Style',
    'Travel',
    'Blogging',
    'Hollywood Shows',
    'Forest Life',
    'Live Stream',
    'Sports',
    'Gaming',
    'Data Structure',
    'Css Updates',
    'Google Policy',
    'Avengers',
    'Sublime Text 3',
    'Vim',
  ];

  nameArr = nameArr.map((name, index) => {
    return (
      <Category
        key={index}
        onClick={setActive(index)}
        name={name}
        active={index == active ? true : false}
      />
    );
  });

  return (
    <div className="categories">
      <section className="category-section">{nameArr}</section>
    </div>
  );
}

export default Categories;

What i want the code to do, is to render a bunch of elements, and when you click on one, it gives the one you click on the active property, and the property from the prevous selected one

I know what the error means, i just don't understand why I am getting it in this situation

Upvotes: 0

Views: 31

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370689

You're calling setActive immediately, when reassigning nameArr:

<Category key={index} onClick={setActive(index)}

This results in new state being set immediately, and the component re-rendering immediately.

Pass in a function that calls setActive, instead of calling setActive yourself:

<Category key={index} onClick={() => setActive(index)}

For similar reasons, the below function logs immediately, instead of waiting for a click:

window.addEventListener('click', console.log('click'));

Also consider passing the active prop regardless if you can, to be more DRY than the if/else:

const nameCategories = nameArr.map((name, index) => (
  <Category key={index} onClick={setActive(index)} name={name} active={index === active} />
));

Upvotes: 1

Related Questions