0

I have an issue with typescript in the following simple component.

This works as expected:

import React from "react";

export default function App() {
  const simpleComp = (shouldSayA: boolean) => {
    return shouldSayA ? <p>a</p> : <p>b</p>;
  };

  return <div>{simpleComp(true)}</div>;
}

However, when I convert the simpleComp function to JSX function component SimpleComp like so:

import React from "react";

export default function App() {
  const SimpleComp = (shouldSayA: boolean) => {
    return shouldSayA ? <p>a</p> : <p>b</p>;
  };
  return <div><SimpleComp shouldSayA={true} /></div>;
}

I get the following error:

const SimpleComp: (shouldSayA: boolean) => JSX.Element
Type '{ shouldSayA: boolean; }' is not assignable to type 'IntrinsicAttributes & boolean'.
  Type '{ shouldSayA: boolean; }' is not assignable to type 'true'.ts(2322)

I can fix the TS error doing something like this:

import React from "react";

export default function App() {
  const SimpleComp = ({shouldSayA}: { shouldSayA: boolean }) => {
    return shouldSayA ? <p>a</p> : <p>b</p>;
  };
  return (
    <div>
      <SimpleComp shouldSayA={true} />
    </div>
  );
}

but I'm sure there's some easier way that I'm missing. Why does TS throws an error in the second example?

1 Answer 1

4

The first argument passed to a component is the object containing all of the props.

If you pass one prop then it will be an object containing a single key:value pair.

That's just how components work. There is no simpler way.


That said, it is usually better to:

  • Define your components once instead of redefining them on every render
  • Define your type as a variable and not inline
import React from "react";

const App = () => {
  return (
    <div>
      <SimpleComp shouldSayA={true} />
    </div>
  );
};

type SimpleCompProps = {
  shouldSayA: boolean;
};

const SimpleComp = ({ shouldSayA }: SimpleCompProps) => {
  return shouldSayA ? <p>a</p> : <p>b</p>;
};

export default App;
Sign up to request clarification or add additional context in comments.

1 Comment

Hi, that's how I ended up doing in my actual code but still thought there would be a more straight-forward way of doing it to keep the structure somewhat similar to the way it works when this <SomeComp .../> component is used as a callable function someComp(true) within JSX. Thanks for your answer though.

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.