1
votes

I am trying to break out components in my app but am running into some trouble understanding how to pass state and props from my parent component to the child components. For context my child component is a table that is rendering a smaller component in the rows.

Right now I have a const called BookComponents that takes a Book and writes to state. Where I am stuck is passing state and props into my BookTable component so that I can render books in the book table and not in the main page Thanks for your help and tips in advance.

MainPage:

import React from 'react';
import type { User, BookType } from '/types';
import Book from './Book';
import BookTable from './BookTable';

type Props = {};

type State = {
  selectedUser: <User> | null,
  books: BookType[]
};

export default class BookPage extends React.PureComponent<Props, State> {
  const BookComponents = this.state.book.map((book) => <Book {...book} />);
  const selectedUser = this.state.selectedUser;

  return (
  <div>

    <div>
      Find Users and their Books
      <Selector
        input={{
          onChange: this.onSelect,
          value: selectedUser,
        }}
        getValue={(user) => user.full_name}
      />

      {selectedUser && (
      <Section>
        <H1>
          {selectedUser.full_name}'s Books
        </H1>
        {BookComponents}
        <BookTable/>
      </Section>)}
    </div>
  </div>
  )
}

BookTable code:

import React from 'react';
import type { User } from '/types';

type Props = {};

type State = {};

export default class BookTable extends React.PureComponent<Props, State> {
  render() {
  return (
    <Section>
      <H1>
        Print User's books here
      </H1>
    </Section>
  );
 }
}
2
I have an answer to a similar question, How to set one component's state from another component in React, hope this helps! - HoldOffHunger
checking it out, thank you! - mrtriangle

2 Answers

2
votes

If i understand you correctly, you just wanna pass state to props of component, nothing else?

In render of MainPage:

<BookTable books={this.state.book} />

In BookTable :

type Props = {
  books: BookType[]
};

export default class BookTable extends React.PureComponent<Props, State> {

  static defaultProps = {
    books: []
  }

  render() {
  return (
    <Section>
      <H1>
        {this.props.books.map((book) => <Book {...book} />)}
      </H1>
    </Section>
  );
 }
}

1
votes

Try to pass state and props from the parent component to the child component like this.

In the parent component, pass the values to the child component.

<BookTable stateaData={this.state} propsData={this.props}/>

In the child component, get the above props as follows.

this.props.stateaData
this.props.propsData