Home > Mobile >  How to pass props to react component in TypeScript?
How to pass props to react component in TypeScript?

Time:01-06

So I have a react component:

function Navbar(isDark: boolean, toggle: () => void) {
   ...
}

Now I want to use this component in another component like so:

function App() {
   return <div> <Navbar isDark={someBoolValue} toggle={someFunc} /> </div>
}

However I get this error:

Type '{ isDark: boolean; toggle: () => void; }' is not assignable to type 'IntrinsicAttributes & boolean'.

How can I fix this?

CodePudding user response:

Props need to be deconstructed because they are passed as objects. You can adjust your NavBar as follows

func Navbar({isDark, toggle}:{isDark:boolean,toggle:() => void}) {
   ...
}

You could also create an interface

interface IProps {
  isDark: boolean;
  toggle: () => void;
}

func Navbar({isDark, toggle}:IProps) {
   ...
}

CodeSandBox : https://codesandbox.io/s/dawn-tdd-g16din?file=/src/Navbar.tsx

This is worth a read : https://stackoverflow.com/a/65948871/15474532

CodePudding user response:

To expound upon the other answer, I would type it as such, which is much more explicit and strongly typed.

type NavbarProps = {
  isDark: boolean;
  toggle: () => void;
}

const Navbar: React.FC<NavbarProps> = ({ isDark, toggle}) => {
  ...
}

CodePudding user response:

React is expecting a functional component to only have one parameter, which is a object containing the props. To immediately fix you problem, you could change this to

function Navbar(props: {isDark: boolean, toggle: () => void}) {
   ...
}

and then access the props in the function as props.isDark or props.toggle. For readability, you may also consider writing this as

interface NavbarProps {
  isDark: boolean;
  toggle: () => void;
}

function Navbar({isDark, toggle}: NavbarProps) {
  ...
}

Generally good practice to put component props in interfaces in the same spot in every file for quick reference.

  • Related