mariocatch
mariocatch

Reputation: 8703

Setting the state with React + TypeScript

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

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>
        );
    }
}

Upvotes: 4

Views: 6782

Answers (2)

Nitzan Tomer
Nitzan Tomer

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

Bal&#225;zs &#201;des
Bal&#225;zs &#201;des

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

Related Questions