Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

42
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

7 months 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

7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos