Home > Software design >  What should be the type of the state using react and typescript?
What should be the type of the state using react and typescript?

Time:01-21

i have code like so,

const [selectedRowId, setSelectedRowId] = React.useState<any | undefined>(
    undefined
); //what should be the type here instead of 'any'


const handleRowClick = React.useCallback(
    row => {
        setSelectedRowId({
            type: row?.original?.type.toLowerCase(),
            id: row?.original?.originalId,
            name: row?.original?.name,
        });
    },
        [setSelectedRowId]
);


return (
    {selectedRowId && (
         <>
             <TabList>
                 <Tab>Controls ({selectedRowId.name})</Tab> //error here
             </TabList>
         </>
     )}
 );

In here what should be the type of selectedRowId instead of 'any'.

i have tried

const [selectedRowId, setSelectedRowId] = React.useState<object | undefined>(
    undefined
);

but this gives error property name doesnt exist on type object on line

Controls ({selectedRowId.name})

could someone help me with this. thanks.

CodePudding user response:

Try to define your object before using the useState and then pass that object to useState. for example in your case:

interface rowType{
      type: String;
      id: number;
       name: Boolean;
    }
    
const [selectedRowId, setSelectedRowId] = React.useState<rowType | undefined>(
  undefined
);

  •  Tags:  
  • Related