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:
Do you want to block assuming that a certain condition is met? Could you please detail your question a little more? :)
– Luiz Felipe
just do not render this component. No condition.
– Emerson Vieira
So just don’t put it in the render.
– Luiz Felipe
then, at first I have no way to control that this component is passed. Hence the question...
– Emerson Vieira