I need to use this react function, but in typescript
const ListItem = ({ text }) => {
let [showMore, setShowMore] = useState(false);
return (
<div className="item">
<div>
<div className={`text ${showMore ? "active" : ""}`}>{text}</div>
</div>
<button onClick={() => setShowMore((s) => !s)}>Show more</button>
</div>
);
};
I have tried something like this, but i am getting some errors
<html>TS2345: Argument of type '(s: showContent) => boolean' is not assignable to parameter of type 'SetStateAction<showContent>'.<br/>Type '(s: showContent) => boolean' is not assignable to type '(prevState: showContent) => showContent'.<br/>Type 'boolean' is not assignable to type 'showContent'.
interface showContent {
state: boolean;
}
let [showMore, setShowMore] = React.useState<showContent>({ state: false });
return (
<div className="item">
<div>
<div className={`text ${showMore ? "active" : ""}`}>{text}</div>
</div>
<button onClick={() => setShowMore((s) => !s)}>Show more</button>
</div>
);
If your intention was to convert the first block to typescript, then you do not need the showContent interface as you're only providing a boolean value.
import React, { ReactNode, useState } from "react";
interface Props {
text: ReactNode;
}
const ListItem = ({ text }: Props) => {
let [showMore, setShowMore] = useState(false);
return (
<div className="item">
<div>
<div className={`text ${showMore ? "active" : ""}`}>{text}</div>
</div>
<button onClick={() => setShowMore((s) => !s)}>Show more</button>
</div>
);
};
See this Typescript Playground
The error you were getting:
Argument of type '(s: showContent) => boolean' is not assignable to parameter of type 'SetStateAction'.
Type '(s: showContent) => boolean' is not assignable to type '(prevState: showContent) => showContent'.
Type 'boolean' is not assignable to type 'showContent'.(2345)
Is trying to tell you that you cannot assign a boolean (meaning true or false) to an object with signature { state: boolean; }. This is why @pilchard suggested to create an object to match your interface ({ state: !s.state }).
But as the code shows above, I don't think you need this object at all, it seems like a typing mistake.