Reputation: 8703
I cannot figure out how to set the state of my React component with TypeScript.
TodoList
TodoList
component, and then immediately set that as the state so I have something to work off ofimport * as React from "react";
import { TodoItem, ITodoItem } from "../TodoItem";
interface ITodoListProps {
items: ITodoItem[];
}
interface ITodoListState {
stateItems: ITodoItem[];
}
export class TodoList extends React.Component<ITodoListProps, Partial<ITodoListState>> {
constructor(props: ITodoListProps) {
super(props);
// Trouble figuring this part out
// I'd like to set the state to the list from the
// props, as a seed.
this.setState({
stateItems: this.state.stateItems
});
}
public render() {
return (
<div>
<ul>
// This should probably be displaying the items from the state, and not the props.
{this.props.items.map((todo, i) => {
return <TodoItem key={i} name={todo.name} />
})}
</ul>
</div>
);
}
}
Upvotes: 4
Views: 6782
Reputation: 164467
You need to pass the props.items
to the state when constructing the initial state:
export class TodoList extends React.Component<ITodoListProps, Partial<ITodoListState>> {
constructor(props: ITodoListProps) {
super(props);
this.state = {
stateItems: props.items
};
}
...
}
Upvotes: 4
Reputation: 13816
In the constructor when setting the initial state, simply assign the value you want to this.state
:
constructor() {
// ...
this.state = { stateItems: ... /* initial value */ }
}
Later in the lifecycle methods or event listeners you can change the state the way you are doing it in the constructor with setState
Upvotes: 3