Nemus
Nemus

Reputation: 1482

Recognising Reactjs children components

I've got this simple code:

import "./styles.css";

export default function App() {
  return (
    <div className="App">
      <Container>
        <A/>
        <B/>
      </Container>
    </div>
  );
}

const A = () => <div>A</div>;

const B = () => <div>B</div>;

const Container = (p) => {
  console.log(p.children);
return <div>C</div>
};

sandbox demo

Let's say I want to recognise from the container component which of its two children is A and which is B. Is there a way to achieve it?

Upvotes: 1

Views: 29

Answers (1)

buzz
buzz

Reputation: 1106

As they are returning object, to check the children you can do the following

const A = () => <div className="A">A</div>;
const B = () => <div className="B">B</div>;
const Container = (p) => {
  {p.children.map((p)=> {
    console.log(p.type.name === "A" ? "do this": "do that" )
  })}
  return <div>C</div>;
};

Upvotes: 1

Related Questions