Search code examples
reactjsreact-component

How can I pass my JSON from SearchBar to the ApartmentByCity and display the needed data from there. How can I do this in ReactJs?


How can I pass my JSON from SearchBar to the ApartmentByCity and display the needed data from there.This SearchBar component is in the App component. How can I do this in ReactJs?I have just started learning ReactJs. I would appreciate the help. Thanks in advance.

SearchBar.js


class SearchBar extends Component {

  constructor (props) {
    super(props)
    this.state = { city: '',
      apartment:[],
    };
  }

  handleSearch (e) {
    this.setState({ city: e.target.value })
  }

  handleGoClick () {
    fetch(`/apartment/city/${this.state.city}`)
      .then(response => response.json())
      .then(data=> this.setState({
        apartment: data
      }))

  };

  render () 
{
    return (
    <div>
        <form onSubmit={e => e.preventDefault()}>
          <input
            type='text'
            size='45'
            placeholder='Barcelona'
            onChange={this.handleSearch.bind(this)}
            value={this.state.city} />
          <button
            type='search'
            onClick={this.handleGoClick.bind(this)}>
            <b> Search </b>
          </button>
        </form>
      </div>

    )
  }
}

export default SearchBar

 The below code is in the ApartmentByCity.js  
import React from 'react';

const ApartmentByCity = (apartment) => {

  return(
    <div>
    <h1> Apartments List </h1>
    <h5>Title: {apartment.title}</h5>
    <h5>Price: {apartment.price} </h5>
    })}
    </div>
  )
};
export default ApartmentByCity;




Solution

  • const ApartmentByCity = (props) => {
      let {apartment} = props;
      return(
        <div>
        <h1> Apartments List </h1>
        <h5>Title: {apartment.title}</h5>
        <h5>Price: {apartment.price} </h5>
        })}
        </div>
      )
    };
    export default ApartmentByCity;
    

    and in the searchbar.js file:

    import ApartmentByCity from './apartment.js';
    

    and in the render of searchbar:

     // this.state.apartments = [{title: 'hello', price: 123}]
     let apartment = this.state.apartments[0];
     let aptProps = {apartment}
     return (
        <div>
            {this.state.apartments.map((apartment, key) => {
                  return (
                      <ApartmentByCity key={`apt-${key}`} apartment={apartment} />
                  );
              })
            }
            <ApartmentByCity apartment={apartment} />
            <ApartmentByCity {...aptProps} />
        </div>
        )