skip to Main Content

I have this component (Blinker2.tsx)

"use client"
import { useState, useEffect } from "react";

const Blinker2 = (props: { interval: number, delay: number }, { children }: Readonly<{ children: React.ReactNode; }>) => {
    const [active, setActive] = useState(false);

    useEffect(() => {
        function toggleActive() {
            setActive(!active)
        }

        setTimeout(() => {
            const intervalId = setInterval(() => {
                toggleActive()
            }, props.interval)
            return () => {
                clearInterval(intervalId);
            };
        }, props.delay);
    }, [active, props.delay, props.interval])

    return (
        <pre>{active ? children : " ".repeat(children?.toString().length ? children?.toString().length : 0)}</pre>
    );
};

export default Blinker2;

As well as the following implementation:

<Blinker2 interval={0} delay={0}>Hello World!</Blinker2>

However, I get the following error from the implementation:

Type '{ children: string; interval: number; delay: number; }' is not assignable to type 'IntrinsicAttributes & { interval: number; delay: number; }'.
  Property 'children' does not exist on type 'IntrinsicAttributes & { interval: number; delay: number; }'.ts(2322)

I figured I could access the "Hello World!" text between the tags using the { children }: Readonly<{ children: React.ReactNode; }> prop, just as the default layout.tsx does, however it doesn’t work here. Is there a better way to access this text or have I done something wrong?

2

Answers


  1. You have incorrect destructuring and an incorrect children type

    It should be something like this:

    const Blinker2 = (props: { interval: number, delay: number, children: React.ReactNode }) => {
      // ...
    };
    
    Login or Signup to reply.
  2. This looks like an issue with the way you are attempting to destructor the props. React expects only one props object and not the way you are handling it with two right now.
    Changing this to the following should resolve your problem:

    ({ interval, delay, children }: { interval: number; delay: number; children: React.ReactNode })
    

    Another way of doing this would be defining a interface for the props of the Blinker2 Component and referencing those, typically this is good practice or I at least prefer it ๐Ÿ™‚

    interface Blinker2Props {
     interval: number;
     delay: number;
     children: React.ReactNode;
    }
    

    and changing the params to

    ({ interval, delay, children }: Blinker2Props)
    

    With both of these you no longer need the props reference and call them directly by their names. Hope this helps!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search