Search code examples
javascriptreactjsreact-bootstrap

Card component is not rendering anything. React bootstrap


I am using card from bootstrap react but it is not rendering anything on the screen, below is my code. Currently it is displaying it but not as intended, I have tried modifying it but it stops working.

I appreciate any help.

function Products(props) {
  let params = useParams()
  let [ product, setProduct ] = useState()
  function loading() {
    return <div className="w-25 text-center"><Spinner animation="border" /></div>
    }
  function Products(products) {
    if (products === null) return;
    return products.map((product) => (
      <ListGroup.Item key={product.Id}>
        <Link to={`/products/${product.name}`} key={product.id}> {product.name}
        </Link>
      </ListGroup.Item>
    ));
  }

  let { id, name, description, price, origin, imgUrl } = product;
  return (
    <>
      <h1>Products</h1>
      <Card className="align-self-start w-25">
      <Card.Body>
      <Card.Title>{origin}</Card.Title>
      <Card.Text>
      <strong>Description:</strong> <span>{description}</span>
          <br/>
          <ProductContext.Consumer>
            {({ products }) => Products(products)}
          </ProductContext.Consumer>
          </Card.Text>
        </Card.Body>
      </Card>
    </>
  );
  if (product === undefined) return loading()
  return product.id !== parseInt(params.productId) ?  loading() : Products()

}

export default Products;

Solution

  • I feel like the logic in your code isn't sound. First of all, useState's product doesn't seem to be used OR set (at least in this code snippet). The products is coming from the ProductContext.Consumer, which we don't know the code for.

    A couple things about your code to fix/look into:

    • use const with useState
    • You aren't using your useState getter or setter in this code snippet.
    • Make sure no locally declared names conflict with imports or other declarations(either rename imports like import BootstrapComponent as BSComponent from "bootstrap" or pick a unique name for your component). You have two Products nested. Whether the scope is sound, name them more purposefully like Products and ProductsWrapper or something.
    • as Xavier said, you have unreachable code

    My guess, is either you have naming conflicts or the Consumer isn't working as expected. Gotta fix your logic and perhaps move the inner Products function out to simplify things for you.