• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

92
Vistas
find a component that contains a certain class name react js

Find the Component from a list of components that contains a certain class name. In my case i want to show the component that has the className "bbb". But I can't seem to find the className. In the code below i made my example with the Name of the component just so I can demonstrate better what i want to achieve:

import React, { useState, useEffect } from 'react';

const Test = () => {

  const One = () => {
    return (
      <h1 className='aaa' >one</h1>
    )
  }
  const Two = () => {
    return (
      <h1 className='bbb' >two</h1>
    )
  }
  const Three = () => {
    return (
      <h1 className='ccc' >Three</h1>
    )
  }

  const [data, setdata] = useState([<One />, <Two />, <Three />])

  return (
    <section>
      {data.filter(x => x.type.name === 'One').map(x => {
      // something like this line below. This doesn't work of course
      // {data.filter(x => x.classList.contains('bbb)).map(x => {
        return <div>{x}</div>
      })}
    </section>
  )
};

export default Test;

I am really new to React js so sorry if this is a stupid question.

Edit: Fixed a typo

almost 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Instead of finding a class name for that filter, you can do it this way.

2 key things in my changes:

const [data, setdata] = useState([One, Two, Three]) You should not call <One/> (under the hook, it's calling React.createElement(One) to render that component)

data.filter((Component) => Component === Two) Check the component reference instead of class name, because class name may be changed and it will cause a bug in your logic

import React, { useState, useEffect } from 'react'

const Test = () => {
  const One = () => {
    return <h1 className="aaa">one</h1>
  }
  const Two = () => {
    return <h1 className="bbb">two</h1>
  }
  const Three = () => {
    return <h1 className="ccc">Three</h1>
  }

  const [data, setdata] = useState([One, Two, Three])

  return (
    <section>
      {data
        .filter((Component) => Component === Two)
        .map((Component) => {
          return (
            <div>
              <Component />
            </div>
          )
        })}
    </section>
  )
}

export default Test

almost 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda