6

I am passing a setState as a prop from a parent component to modify the state on a child component of that parent, on typescript when creating a interface, what is the type of setState?

function App() {
    const [links, setLinks] = useState();

    return (
        <div className='App'>
            <Sidebar setLinks={setLinks} />
            <Main />
        </div>
    );
}

on child:

interface SidebarProps {
    setLinks: ??????;
}


const Sidebar: React.FC<SidebarProps> = ({ setLinks }) => {
    return (
        <div style={sidebar}>
            <button onClick={() => setLinks('1')}>pic1</button>
            <button onClick={() => setLinks('1')}>pic2</button>
        </div>
    );
};
5
  • 2
    appears to be a (link: string) => void; Commented Sep 26, 2020 at 21:58
  • 1
    worth pointing out that in your interface and the App component you've called it setLinks, but in the Sidebar you're using setLink Commented Sep 26, 2020 at 21:59
  • yeah that was my bad, i didnt double check before send. I set (links: string) => void; but still throwing error: Type 'Dispatch<SetStateAction<undefined>>' is not assignable to type '(links: string) => void'. Commented Sep 26, 2020 at 22:02
  • 3
    That tells you the type right there, Dispatch<SetStateAction<undefined>>, which Dispatch and SetStateAction can be imported from react Commented Sep 26, 2020 at 22:08
  • "which can be imported from react" thats what was missing. Commented Sep 26, 2020 at 22:13

3 Answers 3

7

This is my example based on Kyrill's answer.

interface Props {
  editMode: boolean
  setEditMode: React.Dispatch<React.SetStateAction<boolean>>
}

export default function NavToolbar(props: Props): ReactElement {
 
...

I'm sure there are better ways to do this though :)

Sign up to request clarification or add additional context in comments.

Comments

3

Refer the below code:-

function App() {
    const [links, setLinks] = useState<string>();

    return (
        <div className='App'>
            <Sidebar setLinks={setLinks} />
            <Main />
        </div>
    );
}


interface SidebarProps {
    setLinks: Function;
}


const Sidebar: React.FC<SidebarProps> = ({ setLinks }) => {
    return (
        <div style={sidebar}>
            <button onClick={() => setLinks('1')}>pic1</button>
            <button onClick={() => setLinks('1')}>pic2</button>
        </div>
    );
};

2 Comments

isnt it more genetic to say it is a function only?
yeah setLinks is a function.
2

React.Dispatch<React.SetStateAction>

Above string can be replaced if you infer a type for setState (e.g. I assumed setState<string>())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.