简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM