Issue
Here I am converting the typescript class component to functional components but facing some issues I don't know how to fix. Please give me a solution to fix this issue.
class component
import * as React from "react";
import { render } from "react-dom";
import { ReactMultiEmail } from "react-multi-email";
import "react-multi-email/style.css";
const styles = {
fontFamily: "sans-serif",
width: "500px",
border: "1px solid #eee",
background: "#f3f3f3",
padding: "25px",
margin: "20px"
};
interface IProps {}
interface IState {
emails: string[];
}
class App extends React.Component<IProps, IState> {
state = {
emails: []
};
render() {
const { emails } = this.state;
console.log("emails", emails)
return (
<div style={styles}>
<h3>react-multi-email</h3>
<ReactMultiEmail
placeholder="Input your Email Address"
emails={emails}
// onFocus={}
onChange={(_emails: string[]) => {
console.log("_email", _emails)
this.setState({ emails: _emails });
}}
getLabel={(
email: string,
index: number,
removeEmail: (index: number) => void
) => {
return (
<div data-tag key={index}>
{email}
<span data-tag-handle onClick={() => removeEmail(index)}>
×
</span>
</div>
);
}
}
/>
<br />
</div>
);
}
}
render(<App />, document.getElementById("root"));
funcional component
import * as React from "react";
import { render } from "react-dom";
import { ReactMultiEmail } from "react-multi-email";
import "react-multi-email/style.css";
const styles = {
fontFamily: "sans-serif",
width: "500px",
border: "1px solid #eee",
background: "#f3f3f3",
padding: "25px",
margin: "20px"
};
interface IProps {}
interface IState {
emails: string[];
}
export const Email = (props:any) => {
const [emails, setEmail] = React.useState([])
return (
<div style={styles}>
<h3>react-multi-email</h3>
<ReactMultiEmail
placeholder="Input your Email Address"
emails={emails}
// onFocus={}
onChange={(_emails: string[]) => {
console.log("_email", _emails)
setEmail({ _emails });
}}
getLabel={(
email: string,
index: number,
removeEmail: (index: number) => void
) => {
return (
<div data-tag key={index}>
{email}
<span data-tag-handle onClick={() => removeEmail(index)}>
×
</span>
</div>
);
}
}
/>
<br />
</div>
);
}
I am a beginner in react js so I don't know if the right way of conversion or not please share valuable suggestions.
Solution
You've gotten everything right, just need to make some small tweaks to the types.
The default type for useState
is never
. The error you're getting is a side-effect of this.
To fix this you need to set the type for the useState
const [emails, setEmail] = React.useState<Array<string>>([])
Check this codesandbox out as well -> https://codesandbox.io/s/modest-neco-5jmdjg?file=/src/App.tsx
Answered By - Preet Parekh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.