Is there a better way to pass props to a component in React?

This is my main app.js file --- I'm trying to pass down the state values and functions defined here as props to my child components through react-router-dom:

import React, { Component } from 'react'

class BooksApp extends Component {

  state = {
    bookRepository: [{tuna: 'sandwhich'}],
    searchResults: [],
    featuredBook: {}
  }

  fixer = (someBooks, type) => { //code }

  async updateBookRepository(bookID, shelfID) { //code }

  async updateSearchResults(userQuery) { // code }

  async updateFeaturedBook(bookID, shelfID) {//code }


  render() {

    const myProps = {
      bookRepository:this.state.bookRepository,
      searchResults:this.state.searchResults,
      featuredBook:this.state.featuredBook, 
      updateBookRepository:this.updateBookRepository, 
      updateSearchResults:this.updateSearchResults, 
      updateFeaturedBook:this.updateFeaturedBook
    }

    return (
      <div>
        <Route exact path='/' render={(props) => (
          <Bookshelves {...props} {...myProps} />
        )}/>

        <Route path='/search' render={(props) => (
          <Searchpage {...props}  {...myProps}/>
        )}/>

        <Route path='/featuredBook/:bookID' render={(props) => (
          <Featuredbook {...props}  {...myProps}/>
        )}/>

      </div>
    )
  }
}

I'm accessing the props like so:

class Bookshelves extends Component {

  state = {
      shelves: ['currentlyReading', 'wantToRead', 'read']
    }

  render() {

    const { bookRepository } = this.props;

    return (
      <div>
      The props are: {console.log(this.props)}
      </div>
    )
  }
}

And this works, and they show all show up under my props when I attempt to access them, but I'm having trouble udnerstanding WHY I need to define my own object and then pass that down to my child components.

Is there some way that I can assign them to the props-ish object itself so that...

<Route exact path='/' render={(props) => (
  <Bookshelves {...props} />
}/>

...would pass them down?

Answers:

Answer

You can destructure everything in one line

<Route exact path='/' render={(props) => (
  <Bookshelves {...props, ...this.state} />
)}/>

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.