Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the state with React + TypeScript

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>
        );
    }
}
like image 743
mariocatch Avatar asked Mar 10 '23 02:03

mariocatch


2 Answers

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
        };
    }
    ...
}
like image 85
Nitzan Tomer Avatar answered Mar 25 '23 06:03

Nitzan Tomer


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

like image 36
Balázs Édes Avatar answered Mar 25 '23 05:03

Balázs Édes