-3

I want to send variable data Store component to Related Component, I am getting Value const catId=this.state.data.category_id; now i am sending via props to Related Component but I dont know how to use props in Realted Component, i want to assign inside of didmonunt function for example

const url = "https://localhost:3030/api/v5/web/related";
    const postBody = {
      category_id: catId,

here my code: Store.js

import React, { Component } from "react";
// import ReactDOM from "react-dom";
import { Helmet } from "react-helmet";
import { Grid, Image, Icon, Segment, Card  } from "semantic-ui-react";
import TopMenuStrip from "../ComponentList/TopMenuStrip";
import LogoSection from "../ComponentList/LogoSection"; 
import { withRouter } from "react-router-dom";
import OfferList from "./OfferList";
import Related from "./Related";
import CopyRight from "../ComponentList/CopyRight";
import Footer from "../ComponentList/Footer";
import CustomerReview from "./CustomerReview";
class Store extends Component {
  constructor(props) {
    super(props);

    this.state = {
      data: [],
      isLoading: true,
    };
  }

  async componentDidMount() {
    console.log(this.props.match.params.id);
    let url_id = this.props.match.params.id; 
    const url = "https://localhost:3030/api/v5/web/details";
    const postBody = {
      store_id: url_id,
      offer_type: "",
    };
    const requestOptions = {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(postBody),
    };

    fetch(url, requestOptions)
      .then((response) => response.json())
      .then((json) => {
        this.setState({ data: json });
        //console.log(json);
        // console.log(json);
      })
      .catch((error) => console.error(error))
      .finally(() => {
        this.setState({ isLoading: false });
      });
  }

  render() {
    var i;
    // console.log(this.props)
    if (!this.state.data.how_to) {
      return null;
    }
    if (!this.state.data.store_terms) {
      return null;
    }
    const catId=this.state.data.category_id;
    const seokeyWord = this.state.data.seo_keywords;
    const seoDescription = this.state.data.seo_description;
    
    return (
      <>
      <Helmet>
              <meta charSet="utf-8" />
              <title>test</title>
              <meta name="description" content={seokeyWord} />
              <meta name="keywords" content={seoDescription} />
              <meta name="google-site-verification" content="rtIRrUNRpgZ_lFtlfS8LJ0-8j_d569BXS9NOGa_nM6Y" />
               
            </Helmet>
        <TopMenuStrip />
        <LogoSection /> 
        <div>
          <Grid className="storedetails">
            
            <Grid.Column width={11}>
              <div className="storeImage">
                <div className="store-bg">
                  <h2>
                    <span>{this.state.data.store_name}</span>
                    <span className="store-right">
                      {
                        (i =
                          0 < this.state.data.rating ? (
                            <p>
                              <span className="rateNumber">
                                {this.state.data.rating}
                              </span>
                              <Icon id={i} className="star"></Icon>
                            </p>
                          ) : (
                            <p className="no-reviews">No Reviews</p>
                          ))
                      }
                    </span>
                  </h2>
                  <p className="">{this.state.data.summary} </p>
                  {/* <p><span className='rateNumber'>{this.state.data.rating}</span><Icon className='star'/><Icon className='star'/><Icon className='star'/><Icon className='star'/><Icon className='star'/><span className='totalRate'>39000</span></p> */}
                  <div
                    className="store-back"
                    Style={
                      "background: url(" + this.state.data.store_images + ")"
                    }
                  >
                    {/* <Image src= alt="" className='storeImage'/> */}
                    <Image
                      src={this.state.data.logo}
                      alt=""
                      className="storeImageLogo"
                    />
                  </div>
                </div>
                <div className="related-section">
                  <OfferList />
                  </div>
              </div>
            </Grid.Column>
            <Grid.Column className="four-1" width={5}>
              <div className="storeAbout" centered>
                <h3>About</h3>
                <p
                  dangerouslySetInnerHTML={{
                    __html: this.state.data.description,
                  }}
                ></p>
              </div>
              <CustomerReview />
              <Related CatID={catId}/>
            </Grid.Column>
            
          </Grid>
          <Grid className="related-footer">
            <Grid.Column width={16}> 
            
            </Grid.Column>
          </Grid>
        </div>
        <Footer />
        <CopyRight />
      </>
    );
  }
}

export default withRouter(Store);

Related.js

import React, { Component } from  'react';
// import ReactDOM from "react-dom";    
import { Grid, Icon, Segment, Card } from "semantic-ui-react";
import { Link } from "react-router-dom";
import { LazyLoadImage } from 'react-lazy-load-image-component';

class Related extends Component{
  
  constructor(props) {
    super(props);

    this.state = {
      data: [],
      visible: 6,
      isLoading: true,
      dataLoaded: false,
      rec:CatID,
    };
    this.loadMore = this.loadMore.bind(this);
  }
  loadMore() {
    this.setState({
        visible: this.state.visible + 2,
        dataLoaded: this.state.visible >= this.state.data.length
    });
  }
  async componentDidMount() {
    // console.log(this.props.match.params.id); 
    const url = "https://localhost:3030/api/v5/web/related";
    const postBody = {
      category_id: CatID,
      offer_type: "",
    };
    const requestOptions = {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(postBody),
    };

    fetch(url, requestOptions)
      .then((response) => response.json())
      .then((json) => {
        this.setState({ data: json.stores });
        // console.log(json);
        // console.log(json);
      })
      .catch((error) => console.error(error))
      .finally(() => {
        this.setState({ isLoading: false });
      });
  }
 
  render()
    {
      return (
        <>
         <div className="related-stores" centered>
          <h3 className="realted-heading">Related Stores </h3>
        <Grid className="">
        {this.state.data.slice(0, this.state.visible).map((x, i) => {
            return (
              <Grid.Column columns={8} key={i}>
                <Segment>
                  <Card>
                    <Link to={x.store_url}>
                    <div className="image">
                      <LazyLoadImage src={x.image} wrapped ui={false} className="img related"/>
                      </div>
                    </Link>
                    <LazyLoadImage src={x.logo} alt="" className="collection-logo" />
                    <Card.Content>
                      <Link to={x.store_url}>
                        {" "}
                        <Card.Header>{x.name}</Card.Header>
                      </Link>
                      <Card.Description>{x.store_summary}</Card.Description>
                    </Card.Content>
                    <Card.Content extra>
                      <p className="rewards">
                        <span>
                          <LazyLoadImage src="/images/rewards.png" alt="" className="img"/>
                        </span>
                        Cash rewards upto <span>AED {x.cashback}</span>
                      </p>
                      <p className="location">
                        <span>
                          <LazyLoadImage src="/images/location.png" alt="" className="img"/>
                        </span>
                        <span className="store-location" key="index">{x.store_branches}</span>
                        {/* {x.store_branches.map((locations, index) => (
                          <span className="store-location" key="index">
                            {index === 0 ? (
                              <span>{locations.store_location}</span>
                            ) : index >= 1 ? (
                              <span>
                                ,&nbsp;&nbsp;{locations.store_location}
                              </span>
                            ) : null}
                          </span>
                        ))} */}
                      </p>
                    </Card.Content>
                  </Card>
                </Segment>
              </Grid.Column>
            );
          })}
        </Grid>
        {
        !this.state.dataLoaded && (
  <Grid>
     <Grid.Column width={16}>
        <p className="related-load">
           <span
              onClick={this.loadMore}
              className="btn btn-primary load-more"
              Style="cursor:pointer;">
              Loading Store
           </span>
       </p>
     </Grid.Column>
   </Grid>
)
}
        </div>
      </>
     
        )
    }
  }

export default Related;
svcodes
  • 11
  • 3
  • The question is poorly formatted and does not explain the problem well. Please try to better explain what you're trying to accomplish. If you have tried a solution but it doesnt seem to work, please tell us how it behaves right now as opposed to how it SHOULD behave. On another note, there are 2 ways to pass data between components in react. One is called prop-drilling where you pass state when you want to pass data to child and setState when you want child to set data of parent. The other way is by using a global state menagment tool such as Redux. – Dimitar Aug 24 '21 at 11:49
  • Impossible to understand what you want here. – Ricardo de Paula Aug 24 '21 at 11:54

1 Answers1

0

In the Store component, pass storeCategory as props to the Related component.

In the Related component, access categoryId from the props and set it as category_id in postBody.

class Related extends Component {
  ...
  async componentDidMount() {
    ...
    const postBody = {
      category_id: this.props.categoryId,
      ...
  }
  ...
}

class Store extends Component {
  ...
  render() {
    ...
    return(
      ...
      <Related categoryId={storeCategory} />
      ...
    );
  }
}

Explanation:

Related is a child of Store (parent).

To pass data from a parent component to a child component, use props.

Set an attribute on , e.g. categoryId, and assign the data (storeCategory) to it:

<Related categoryId={storeCategory} />

Store will then receive categoryId among its props. In Store, you can thus access categoryId from the props:

this.props.categoryId

Further reading:

Akasha
  • 969
  • 5
  • 8