Setting the state with React + TypeScript

Viewed 6362

I cannot figure out how to set the state of my React component with TypeScript.

  • I'm making a simple Todo list
  • I have a component for the entire list: TodoList
  • I want to seed the list with some items to play around with
  • I figured I'd send in a simple array as the props to the TodoList component, and then immediately set that as the state so I have something to work off of
import * 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>
        );
    }
}
2 Answers
Related