Is there any way to block the rendering of a particular component in React?

Asked

Viewed 351 times

1

I need to block the rendering of a certain type of component, for example:

<td>{props.children}</td>

I need to capture the component that can be passed to Children and block its rendering. If I want to block the p tag, how would I do that? Is there any better way to do that?

  • Do you want to block assuming that a certain condition is met? Could you please detail your question a little more? :)

  • just do not render this component. No condition.

  • So just don’t put it in the render.

  • then, at first I have no way to control that this component is passed. Hence the question...

1 answer

3

If you want to filter some element from prop children React, you’ll need to use the API React.Children:

You can then use the method React.Children.toArray() to create a array based on property children and filter only the elements you want to render.

For that, since we’re dealing with array, it is convenient to use the method filter.

Below I leave an example:

function Container(props) {
  return (
    <div>
      <p>Componentes renderizados:</p>
      <hr />
      {React.Children.toArray(props.children).filter(
        (child) => child.type !== 'h2'
      )}
    </div>
  )
}

function App() {
  return (
    <Container>
      <h1>[h1] Este componente será renderizado.</h1>
      <h2>[h2] Este componente NÃO será renderizado.</h2>
      <h3>[h3] Este componente tanbém será renderizado.</h3>
    </Container>
  )
}

ReactDOM.render(<App />, document.getElementById('root'))
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>

<div id="root"></div>

Reference:

  • Thanks, Luiz. I decided otherwise, but here’s the tip. Obg :D

  • Cool! I can know how you did? :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.