Hi I am trying to create a component that returns a react bootstrap toast and toast container but am getting a typescript error.
const Notification = (props: {
variant: string,
header: string,
message: string,
position: string
}) => {
const [show, setShow] = useState(true);
return (
<ToastContainer
className="mt-4 pt-5"
// position={"top-center"}
position={props.position}
style={{ zIndex: 1 }}
>
<Toast
onClose={() => setShow(false)}
show={show}
delay={7000}
autohide
bg={props.variant}
>
<Toast.Header closeButton={false}>
<strong className="text-center">{props.header}</strong>
</Toast.Header>
<Toast.Body className="text-white text-center">{props.message}</Toast.Body>
</Toast>
</ToastContainer>
)
}
So I pass in
<Notification
variant={"success"}
header={"Success"}
message={"Item successfully added to cart."}
position={"top-center"}
/>
Everything works like props.message, props.variant, etc. For some reason though I get the following error for position.
Type 'string' is not assignable to type 'ToastPosition | undefined'.ts(2322) ToastContainer.d.ts(5, 5): The expected type comes from property 'position' which is declared here on type 'IntrinsicAttributes & Omit<Omit<DetailedHTMLProps<HTMLAttributes, HTMLDivElement>, "ref"> & { ...; }, BsPrefixProps<...> & ToastContainerProps> & BsPrefixProps<...> & ToastContainerProps & { ...; }' (property) ToastContainerProps.position?: ToastPosition | undefined
The code still works (it gets "top-center" from the props and places it correctly) but it gives a type error. I get that it is saying it can't be a string or undefined. I don't see why this case is different than the bg={props.variant} though. In both cases there is a default value, and it is being changed to the prop. I even tried putting in a position={props.position ? props.position : "top-center"} thinking that might fix it but it still has the same error.
The type of position
in ToastContainer
is ToastPosition | undefined
and not string
.
To fix it replace position: string
with position?: ToastPosition
in type declartion of Notification component. The question mark makes the prop optional thus adding undefined
.
You can import ToastPosition as follow: import ToastContainer, { ToastPosition } from "react-bootstrap/ToastContainer";
The line "Type 'string' is not assignable to type 'ToastPosition | undefined'" says the same thing.