M
M
Maksipes2020-04-26 18:11:53
React
Maksipes, 2020-04-26 18:11:53

How to find out how many children a React component returns?

To draw buttons in the menu, the application does this: each Button wraps in a Wrapper, which, depending on some conditions, returns the original Button component or not.

Pretty comfortable and pretty. Buttons in an array with their wrappers, which, depending on the route, data availability, or some other conditions, return buttons or not, as a result, an easily scalable dynamic menu.

But the question arose - how to know in advance how many buttons will be rendered? The main thing is to check for 0, is there at least one button?

In theory, you need to somehow render this construction into a variable, but how?

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <Wrapper>
        {({ label, icon, onClick }) => (
          <Button
            onClick={onClick}
            icon={icon}
          >
            {label}
          </Button>
        )}
      </Wrapper>
    </div>
  );
}


export class Wrapper extends React.Component {
  render() {
    const param = true;
    const { children } = this.props;

    const node = children({
      label: "Кнопка1",
      onClick: () => alert("onClick")
    });

    return Boolean(param) && node;
  }
}


export class Button extends React.Component {
  render() {
    const { onClick } = this.props;

    return <button onClick={onClick}>{this.props.children}</button>;
  }
}


Here is an example - https://codesandbox.io/s/frosty-aryabhata-1zefx

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Robur, 2020-04-26
@Robur

at runtime App you don't yet have the information about whether the buttons will be rendered or not. You simply return a handle to the virtual tree.
"Rendering" somewhere into a variable is a so-so idea.
Possible solutions
are to move logic from wrappers somewhere higher (where you need to use this information). For example, where Wrapper will simply contain information about the condition, and WrappersList will directly do the filtering, so you can do something else there. Or, as an option, take the logic out of the components so that it can be used independently in Wrapper and WrapperList
- build something to pass the state of whether the wrapper worked or not to the parent component (callbacks for example) and change the rendering in the parent component accordingly. The main thing here is to do it carefully and without a rake.

A
abberati, 2020-04-26
@abberati

react.children.count

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question