msaba
msaba

Reputation: 76

React condition rendering component typescript

I have a component called Visible with two props: condition and children the flow is if the condition is true the component will return the children(s) and if not it will return null (just like condition rendering), but VScode doesn't recognized that what the condition is doing and throw an error for children (the variable may be null)

is there a way to define a type for this component return that VScode recognizes the condition checks the variables?

Visible.ts:

interface IVisible {
    condition: any
    children: React.ReactNode
}

function Visible(props: IVisible) : React.ReactNode {
    const {condition, children} = props

    if( !(!!condition) ) return null;
    
    return <Fragment>{children}</Fragment>
}

usage ex:

const [banana, setBanana] = useState<undefined|string[]>(["foo","bar"])

return (
    <Visible condition={banana}>
        <ul>
        {banana.map(e => <li key={e}>{e}</li>) }
        </ul>
    </Visible>
)

Upvotes: 0

Views: 2029

Answers (1)

Ivan Popov
Ivan Popov

Reputation: 696

Try this! Declare return type is JSX.Element

interface IVisible {
    condition: boolean;
    children: React.ReactNode;
}

const Visible = ({ condition, children }: IVisible): JSX.Element =>
    condition ? <Fragment>{children}</Fragment> : null;

But I still recommend using just conditional rendering.

I don’t understand why to make a component when there is an already implemented opportunity for this.

When there are additional calculations or some other peculiarities, then yes, you can make a component.

But when you just need to render a component by a simple condition, it seems to me that you shouldn't make an additional component for this.

const [banana, setBanana] = useState<string[]>(['foo', 'bar']);

return (
    <div>
        banana.length > 0 && (
            <ul>
                {banana.map(e => (
                    <li key={e}>{e}</li>
                ))}
            </ul>
        )
    </div>
);

Upvotes: 1

Related Questions