nathannewyen
nathannewyen

Reputation: 253

How can I pass props to another components with in reactjs

I'm trying to pass product data from AllProducts component to Product component.

AllProducts.jsx: is showing all the products I have and Product.jsx will show specific product and how can I pass data to Product.jsx?

Here is my AllProducts.jsx:

const AllProducts = (props) => {
  const [products, setProducts] = useState([]);

  const getProductsAPI = () => {
    axios
      .get("http://localhost:8000/api/products")
      .then((res) => {
        setProducts(res.data);
        getProductsAPI();
      })
      .catch((err) => {
        console.log(err);
      });
  };

  useEffect(() => {
    getProductsAPI();
  }, [props]);

  return (
    <div>
      <table className="table table-bordered table-hover">
        <thead>
          <tr>
            <th>#</th>
            <th>Title</th>
            <th>Action</th>
          </tr>
        </thead>
        <tbody>
          {products.map((product, i) => (
            <tr key={i}>
              <th scope="row">{i}</th>
              <td>{product.title}</td>
              <td>
                <Link to={`/products/${product._id}`}> View </Link>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

and here is my Product.jsx:

const Product = (props) => {
  return (
    <div className="container">
      <h4>{props.product.title}</h4>
    </div>
  );
};

export default Product;

Here is my project github if you want to look at all the code I have: https://github.com/nathannewyen/full-mern/tree/master/product-manager

Upvotes: 1

Views: 61

Answers (1)

Eric
Eric

Reputation: 1347

  • If the data is fully loaded for each product in AllProducts, and you don't want to make another API call by product id in the Product component, in this case, you don't have to use a route link to view Product, just make a conditional rendering to show Product component inside AllProducts component. pseudo-code as below,

        const [showProduct, setShowProduct] = useState(false);
        const [currentProduct, setCurrentProduct] = useState();
        const showProduct = (product) => {
          setShowProduct(true);   
          setCurrentProduct(product);         
         }     
         <tbody>
            {products.map((product, i) => (
              <tr key={i}>
                <th scope="row">{i}</th>
                <td>{product.title}</td>
                <td>
                  <button type="button" onclick = {showProduct(product)}>View</button>
                </td>
              </tr>
            ))}
          </tbody>
    
        return (showProduct ? <Product /> : <AllProucts/>)
    
  • If you also need to make another API call to get extra data for each product, then use the router link but perhaps you can not pass props.

Upvotes: 1

Related Questions