Reputation: 55
recently in my work we are using react with typescript.. And seriously I'm so newbie and I feel really dummy to make any functions.. with it.. But in my free time, I try to learn typescript more.. I'm a little bit confused with hooks in typescript.. Somebody could let me know how to map an object in an object array? I've tried many ways and even checked on stackoverflow similar issues, but I couldn't solve mine..
E.g. usually if I'm using ES6+ I feel really comfortable so in this case, I'd rather show you what I want to get. If I get this easy example I think I will understand typescript more.
const App = () => {
const [data, setData] = data([]);
const [query, setQuery] = query("");
const handleSubmit = (e) => {
e.preventDefault();
if (query) {
const newItem = {id: new Date().getTime().toString(), query};
setData([...data, newItem]);
}
}
return (
<section className="section">
<form onSubmit={handleSubmit}>
<div className="form-control">
<label forHTML="input">Add new</label>
<input type="text" id="input"/>
<button type="submit">Add</button>
</div>
</form>
<article className="someData">
{data.map(item => {
return <div className="box">
<h2>{item.title}</h2>
</div>
})}
</article>
</section>
)
}
I know this example has not much sense, but If I'd know how to write it in typescript I could get know-how typescript works like. I've read the documentation and All the time I want to map my object I always type it as Array or object or even as an "any" and nothing does work :( I'm just curious how this function written in ES6 could look like in typescript..
Upvotes: 0
Views: 3854
Reputation: 340
import React, { useState } from 'react';
interface Data {
id: string;
query: string;
}
const App: React.FC<{}> = () => {
const [data, setData] = useState<Data[]>([]);
const [query, setQuery] = useState<string>('');
const handleSubmit = (e: React.FormEvent<HTMLFormElement>): void => {
e.preventDefault();
if (query) {
const newItem: Data = { id: new Date().getTime().toString(), query };
setData([...data, newItem]);
}
};
return (
<section className="section">
<form onSubmit={handleSubmit}>
<div className="form-control">
<label forHTML="input">Add new</label> {//TS Error, invalid prop forHtml}
<input type="text" id="input" />
<button type="submit">Add</button>
</div>
</form>
<article className="someData">
{data.map((item: Data, i: number) => {
return (
<div key={i} className="box">
<h2>{item.title}</h2>{ // TS Error no title in data}
</div>
);
})}
</article>
</section>
);
};
export default App;
Upvotes: 1