2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

React + TypeScriptで location.state を使う

Last updated at Posted at 2020-08-11

React(TS)における、コンポーネント間のデータの受け渡しにlocation.stateを使うときの方法。

やりたいこと

bookというstateを表示する Book.tsx と、 そのbook情報を編集する EditBook.tsx があったとします。
このとき Book.tsx 内で編集ボタンをクリックするとbookの情報を EditBook.tsx に渡したい。

方法

Book.tsx

interface BookState {
    book: {
        id: number
        title: string
        author: string
    }
}

class Books extends Component<{}, BookState> {
    state: State {
        book: {
            id: props.id,
            title: props.title,
            author: props.author,
        }
    }

    // bookの内容をEditBookにわたす
    handleEditBook = () => {
        history.push({
            pathname: '/edit_book',
            state: { Book: this.state.book}
        });
    }
}
EditBook.tsx

interface EditBookProps {
    location: any
}

interface EditBookState {
    book: {
        id: number
        title: string
        author: string
    }
}

class EditBook extends Component<EditBookProps, EditBookState> {
    constructor(props: any) {
        super(props);
        this.state = {
            // this.props.location.stateで受け取り
            book: {
                id: this.props.location.state.Book.id,
                title: this.props.location.state.Book.title,
                author: this.props.location.state.Book.author,
            }
        };
    }
}
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?