Hi there i'm coding simple todo apps with react.js/typescript. i'm stuck with calling repeatedly todos
i could call todo at 1) and 3) but I COUDNT call 2) .
whats the difference. maybe my interface type makes bad in todo.type.tsx
?
<TodoListItem todo={todos[0]} />
{todos.map(todo=> { <TodoListItem todo={todo} /> })}
{todos.map(todo => (<li>{todo.text} - {todo.email2}</li> ))}
or my Props2 calling in todo.tsx
is bad ?
React.FC<Props2> = ({ todo })
this is shown
==== ( localhost:9000 rendering shows this ) ======
text1"[shown in TodoListItem]"contato@gabrielrufino.com
text1 - contato@gabrielrufino.com
text2 - darthvader@starwars.com
src/pages/index.tsx
import { TodoListItem } from '../components/todo';
export default function IndexPage(){
const [todos, setTods] = useState<Todo[]>([
{
text: 'todo1',
email2: '[email protected]'
},
{
text: "todo2",
email2: '[email protected]'
}
])
return (
<Layout>
<TodoListItem todo={todos[0]} /> // ★I can call (★1)
<ul>
{todos.map(todo=> {
<TodoListItem todo={todo} /> // ★I CANT call (★2)
})}
</ul>
<ul>
{todos.map(todo => (
<li>{todo.text} - {todo.email2}</li> // ★I can call (★3)
))}
</ul>
</Layout>
)
}
src/model/todo.type.tsx
interface Todo {
text: string;
email2: string;
}
interface Props2 {
todo: Todo;
}
src/components/todo.tsx
import React, { FC } from 'react';
export const TodoListItem: React.FC<Props2> = ({ todo }) => {
return (
<li>
{todo.text}
<br> "shown in TodoListItem"
</br>
{todo.email2}
</li>
);
};
CodePudding user response:
The issue was that it was not returning at all.
Try
<ul>
{todos.map((todo: Todo) => (
<TodoListItem todo={todo} />
))}
</ul>
or
<ul>
{todos.map(todo=> {
return <TodoListItem todo={todo} />
})}
</ul>
instead of
<ul>
{todos.map(todo=> {
<TodoListItem todo={todo} /> // ★I CANT call (★2)
})}
</ul>
Code sandbox => https://codesandbox.io/s/nervous-bartik-vl8hs
CodePudding user response:
You have made a bracketing error. For any function in JS/TS the ()
signify returning (you don't even have to use the keyword return
) whereas {}
signifies simply running the function
In your index.tsx
file :
import { TodoListItem } from '../components/todo';
export default function IndexPage(){
const [todos, setTods] = useState<Todo[]>([
{
text: 'todo1',
email2: '[email protected]'
},
{
text: "todo2",
email2: '[email protected]'
}
])
return (
<Layout>
<TodoListItem todo={todos[0]} /> // ★I can call (★1)
//Here, inside the map function you have used "{}" instead of "()" so the map function is simply iterating and not returning anything.
<ul>
{todos.map(todo=> {
<TodoListItem todo={todo} /> // ★I CANT call (★2)
})}
</ul>
<ul>
{todos.map(todo => (
<li>{todo.text} - {todo.email2}</li> // ★I can call (★3)
))}
</ul>
</Layout>
)
}
The fixes for this could be
<ul>
{todos.map((todo: Todo) => (
<TodoListItem todo={todo} />
))}
</ul>
or
<ul>
{todos.map(todo=> {
return <TodoListItem todo={todo} />
})}
</ul>