Accessing React components child elements

Hello. I have a function in a file which children I want to access.
Here’s my functional component

const primary = (args) => {

  return (
    <ReactPagination {...args}>

      <h1>Hello</h1>

      <h1>Sec</h1>

    </ReactPagination>
  );
};

Now I need to access all the children of the <ReactPagination> component, how can I do so? I want to make a variable below which will store how many children does <ReactPagination> component has.

Do you mean access to the children from inside the ReactPagination component?

props.children

1 Like

No, that’s the problem I’m facing here :sweat_smile:

I want to access it from outside the primary component so the code should look like this

const primary = (args) => {

  return (
    <ReactPagination {...args}>

      <h1>Hello</h1>

      <h1>Sec</h1>

    </ReactPagination>
  );
};

let childrenLength = primary.children[0].children.length /// I know what I wrote here makes no sense, I did it just to show what I have in mind

<ReactPagination> is imported from its separate file

Not sure I really understand the use case here. Can you explain what it is you are trying to achieve?

Maybe you can pass a function down that when invoked gets passed back what you need from the child(ren).

First of all, why is “primary” lowercase instead of PascalCase?

And I second the confusion over why you would want to do this. If you write it, you should no how many children there are. If it’s dynamic, you should still be able to figure out how many there are. I can’t imagine a use case for what you are trying to do - there should be easier and safer ways to do what you want.

That being said, if I understand what you want to do, you should be able to instantiate the component and then drill into it. For example:

primary().props.children.length

This should tell you how many immediate children there are of the main JSX component. There is an example pen here.

I can’t guarantee that this will always work as expected always and everywhere since we seem to be going off-label here. And I caution that you may be trying to do something that React does not want you to do, or at least there is a much better way to do. I almost didn’t reply because I don’t want to enable you going down the wrong rabbit hole.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.