Search code examples
reactjsjsxstyled-componentsrecoiljs

How can I add CSS class when I click on React?


My development environment: react, recoil, javascript, styled-component.

When I click on the technology stack for each field classified as a tab, I want to change the CSS only when it is clicked and included in the selected Tags.

enter image description here


const [selectedTags, setSelectedTags] = useRecoilState(selectedTagsState);

  const tabContArr = [
    {
      tabTitle: 'FE',
      tabCont: ['JavaScript', 'TypeScript', 'React', 'Vue', 'Svelte', 'Nextjs'],
    },
    {
      tabTitle: 'BE',
      tabCont: [
        'Java',
        'Spring',
        'Nodejs',
        'Nextjs',
        'Go',
        'Kotlin',
        'Express',
        'MySQL',
        'MongoDB',
        'Python',
        'Django',
        'php',
        'GraphQL',
        'Firebase',
      ],
    },
    {
      tabTitle: 'etc',
      tabCont: [],
    },
    
  ];

  const onTagClick = (e) => {
    const newSelectedTags = [...selectedTags];

    const filterTarget = newSelectedTags.filter(
      (el) => el.tagName === e.target.textContent,
    );

    if (filterTarget.length === 0 && newSelectedTags.length < 5) {
      let tagObj = {};
      tagObj.tagName = e.target.textContent;
      newSelectedTags.push(tagObj);
      setSelectedTags(newSelectedTags);
    } else if (
      filterTarget.length !== 0 ||
      selectedTags.length >= 5
    ) {
      {
        (''); // nothing change
      }
    }
  };

          // FE, BE Choose
          tabContArr[activeIdx].tabCont.map((skillTag, idx) => {
            return (
              <div
                key={idx}
                className={
                  // HERE!!!
                  selectedTags.includes(skillTag)
                    ? 'skill-tag skill-selected-tag'
                    : 'skill-tag'
                }
                onClick={onTagClick}
                aria-hidden="true"
              >
                {skillTag}
              </div>
            );
          })

I tried to write the code like the one marked "HERE!!!" but it didn't work when I did this. Please help me on how to change the CSS (Class) only for the names in the selected Tag!!

className={
  // HERE!!!
  selectedTags.includes(skillTag)
    ? 'skill-tag skill-selected-tag'
    : 'skill-tag'
  }

Solution

  • In tabContArr[activeIdx].tabCont.map((skillTag, idx) => {, skillTag is a string, while selectedTags is an array of objects, like this: [{tagName: 'Java'}, {tagName: 'Spring'}, ...]. You are determining whether the array of objects contains a string, which will never occur. console.log(selectedTags, skillTag) will make it easier to understand.