react typescript what type is setState?

Viewed 2837

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>
    );
};
3 Answers

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>
    );
};

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 :)

React.Dispatch<React.SetStateAction>

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

Related