Search code examples
react-typescript

How to filter the props.children


I use props.children in function component like below which is working fine as in all children renders fine in UI.

function Footer(props: FooterProps) {
   return (
     <div>
        {props.children}
    </div>
   );
};

However, I need to filter the props.children based on some properties of child and put them in different div. There are no errors in console, but child components does not render.

function Footer(props: FooterProps) {
   return (
     <div>
        {props.children?.map(child => {
            if (child.align === "right") { //no probs with this condition, code executes as expected.
                <div> // grouping into another div
                    {child}
                </div>
            }
            else {
                { child }
            }
        })}
    </div>
   );
};

Any idea what could be wrong here?


Solution

  • You aren't returning anything in your map callback, it's becoming an array of undefined which React is designed not to render anything for. If you wrap your two intended values in return statements it should work as intended.

    Here's what that would look like:

    function Footer(props: FooterProps) {
       return (
         <div>
            {props.children?.map(child => {
                if (child.align === "right") { //no probs with this condition, code executes as expected.
                    return (
                        <div> // grouping into another div
                            {child}
                        </div>
                    );
                }
                else {
                    return child;
                }
            })}
        </div>
       );
    };
    

    I'm not sure if this is really the correct way to do this, generally speaking I'd discourage changing a child directly in this way after receiving it and looking for a more compositional approach, but in the case that you do need to do so, you might should be using the React.Children.map method: https://reactjs.org/docs/react-api.html#reactchildrenmap