JoeBe
JoeBe

Reputation: 1290

How to conditionally add a child component to a parent component in React?

Consider an array like this:

const myArray = [1,2,3]

Depending on the length of this array (which keeps changing only between 2 and 3), I want to add or remove a react-native-svg component which display this value.

This is how I have approached it so far (I know this code will not work):

const myComponent = (props) => {
    const [myArray, setMyArray] = useState([1,2,3]);

    const mySVGComponents = useEffect(() => {
        //It is ensured that the array has at least two values
        let GroupWrapper = (() => {
            return (
                <G>
                    <SVGText>{myArray[0]}</SVGText>
                    <SVGText>{myArray[1]}</SVGText>
                </G>
            )
        })

        if (myArray.length === 3) {
            GroupWrapper = (() => {
                return (
                    <GroupWrapper>
                        <SVGText>{myArray[2]}</SVGText>
                    </GroupWrapper>
                )
            })
        }

        return GroupWrapper;

    }, [myArray]);

    return (
        <G>
            {mySVGComponents}
        </G>
    )
}

How can I inject SVGText components into the <G> component conditionally based on the length of myArray?

Upvotes: 1

Views: 341

Answers (2)

Kailash
Kailash

Reputation: 877

Only change your "mySVGComponents" to below given code.

const mySVGComponents = useEffect(() => {
            //It is ensured that the array has at least two values

             let GroupWrapper = (() => {

               return (
                    <G>
                      {
                       myArray.map(item => <SVGText>{item}</SVGText>)
                      }  
                    </G>
                )
            })
            return GroupWrapper;

        }, [myArray]);

Upvotes: -1

hiddenuser.2524
hiddenuser.2524

Reputation: 4988

Rendering an array of items in React is not as complicated as you are trying to do it here. You can read mode about that here: https://reactjs.org/docs/lists-and-keys.html

Specifically for your case, you first have to remove the useEffect, you are not supposed to use it like that (https://reactjs.org/docs/hooks-effect.html). All you have to do is just map the array in the return statement, take a look at this:

export const MyComponent = (props) => {
    const [myArray, setMyArray] = useState([1,2,3]);
    return <G>{myArray.map(item => <SVGText key={item}>{item}</SVGText>)}</G>;
}

This way you are rendering each item in the array, and it will be automatically rerendered when you update you array using setMyArray.

Upvotes: 2

Related Questions