Netflix Clone Images won't show in rows - reactjs

I'm newer to coding and have been creating a Netflix clone with react.
I'm trying to create rows and fetch the images into the rows with the tmdb API.
I have fetched the data into my console but I can't get the images to render on the UI.
I know its the src={} in my in my Row.jsx file.
Can anyone help me with fixing this please, I've tried following the documentation for tmdb and i still couldn't get it to work.
Thanks in advance :)
Row.jsx
import axios from 'axios';
import React, { useState, useEffect } from 'react';
const Row = ({ title, fetchURL }) => {
const [movies, setMovies] = useState([]);
useEffect(() => {
axios.get(fetchURL).then((response) => {
setMovies(response.data.results);
});
}, [fetchURL]);
console.log(movies);
return (
<>
<h2 className="text-white font-bold md:text-xl p-4">{title}</h2>
<div className="relative flex items-center">
<div id={'slider'}>
{movies?.map((item, id) => {
<div className="w-[160px] sm:w-[200px] md:w-[240px] lg:w-[280px] inline-block cursor-pointer relative p-2">
<img
src={`https://image.tmdb.org/t/p/original/${item?.backdrop_path}`}
alt={item?.title}
/>
</div>;
})}
</div>
</div>
</>
);
};
export default Row;
Requests.js
const requests = {
requestPopular: `https://api.themoviedb.org/3/movie/popular?api_key=${key}&language=en-US&page=1`,
requestTopRated: `https://api.themoviedb.org/3/movie/top_rated?api_key=${key}&language=en-US&page=1`,
requestTrending: `https://api.themoviedb.org/3/movie/popular?api_key=${key}&language=en-US&page=2`,
requestHorror: `https://api.themoviedb.org/3/search/movie?api_key=${key}&language=en-US&query=horror&page=1&include_adult=false`,
requestUpcoming: `https://api.themoviedb.org/3/movie/upcoming?api_key=${key}&language=en-US&page=1`,
};
export default requests;
Home.jsx
import React from 'react';
import Main from '../components/Main';
import Row from '../components/Row';
import requests from '../Requests';
const Home = () => {
return (
<>
<Main />
<Row title="Up Coming" fetchURL={requests.requestUpcoming} />
<Row title="Popular" fetchURL={requests.requestPopular} />
<Row title="Trending" fetchURL={requests.requestTrending} />
<Row title="Top Rated" fetchURL={requests.requestTopRated} />
<Row title="Horror" fetchURL={requests.requestHorror} />
</>
);
};
export default Home;

Related

Trying to change my image - ADD to ADDED when onclick on the img, no idea how to go about it. I am new to React

import React, { useState } from 'react';
import NavBar from "../../components/navBar/navbar";
import "./profile.scss"
import add from './Images/add.png'
import added from './Images/added.png'
const Profile = () => {
return (
<div className="navbar-display">
<NavBar/>
<div className="right" >
<img id='imageid' src={add} alt='' onClick={''}/>
</div>
</div>
)
}
export default Profile;
<div className="right" >
<img id='imageid' src={add} alt='' onClick={''}/>
</div>
This is the section im having troubles with. Ive tried lots of online methods but constantly ran into errors and cant seem to find a definitive way to onclick change image with ReactJS
just simply use the useState to keep track of your image, something like this:
import React, { useState } from "react";
import NavBar from "../../components/navBar/navbar";
import "./profile.scss";
import add from "./Images/add.png";
import added from "./Images/added.png";
const Profile = () => {
const [image, setImage] = useState("left");
const handleClick = () => {
if (image === "left") {
setImage("right");
} else {
setImage("left");
}
};
return (
<div className="navbar-display">
<NavBar />
<div className="right">
<img
id="imageid"
src={image === "left" ? add : added}
alt=""
onClick={() => handleClick()}
/>
</div>
</div>
);
};
I ended up fixing this issue by using state as above mentioned like this. Thank you for the reply <3
const [isFollowed, setIsFollowed] = useState(false);
const [isFollowedtext, setIsFollowedtext] = useState(false);
const followHandler = () => {
setIsFollowed(!isFollowed);
setIsFollowedtext(!isFollowedtext);
};
<div className="right" onClick={followHandler}>
{isFollowed ?
<p>Connected with user!</p> : <p>Connect with user!</p>}
{isFollowedtext ?
<img src={added} alt="" /> : <img src={add} alt="" />}
</div>

How to add spinner while loading data in react.js?

I want to add spinner while loading data from database. For fetching data I am using react-hook. Here is my code ,how can I add spinner here?
import React from "react";
import { useNavigate } from "react-router-dom";
import useInventories from "../../../hooks/useInventories";
import Inventory from "../Inventory/Inventory";
const Inventories = () => {
const [inventories] = useInventories();
return (
<>
<div id="inventory" className="container mt-5 ">
<h2 className="text-center my-5 text-primary ">Inventory</h2>
<div className="row row-cols-1 row-cols-md-3 g-4 border-1 ">
{inventories.slice(0, 6).map((inventory) => (
<Inventory key={inventory._id} inventory={inventory}></Inventory>
))}
</div>
</div>
</>
);
};
export default Inventories;
It take a little bit time to load data from mongodb. So I want to add spinner loading before that.
You can do solution with useEffect. Basically initial loading is true and it becomes false when you have inventories data. I also see that you are using tailwind so you can set spinner icon animation directly with animate-spin
import React from "react";
import { useNavigate } from "react-router-dom";
import useInventories from "../../../hooks/useInventories";
import Inventory from "../Inventory/Inventory";
const Inventories = () => {
const [inventories] = useInventories();
const [loading, setLoading] = useState(true)
useEffect(() => {
if(inventories?.length > 0) {
setLoading(false)
}
}, [inventories])
return (
<>
{loading <SpinnerComponent/> }
{!loading
<div id="inventory" className="container mt-5 ">
<h2 className="text-center my-5 text-primary ">Inventory</h2>
<div className="row row-cols-1 row-cols-md-3 g-4 border-1 ">
{inventories.slice(0, 6).map((inventory) => (
<Inventory key={inventory._id} inventory={inventory}></Inventory>
))}
</div>
</div>}
</>
);
};
export default Inventories;

Error : "createSliderWithTooltip is not a function"

Im trying to implement the rc-slider for the web app however the rc-slider tooltip isnt recognized and shows an error of "createSliderWithTooltip is not a function" , which im not sure why .
For implementation of rc-slider i followed the rc-slider documentation which is the same way i have implemeneted in the code of home.js somehow im getting an error in console and nothing shows at all.
Thanks in advance.
Home.js
import React, { Fragment, useEffect , useState } from 'react'
import MetaData from './layouts/MetaData'
import { useDispatch , useSelector } from 'react-redux'
import { getProducts } from '../actions/products'
import Product from './products/Products'
import Loader from './layouts/Loader'
import { useAlert } from 'react-alert'
import Pagination from "react-js-pagination";
import {useParams} from 'react-router-dom'
import Slider from 'rc-slider'
import 'rc-slider/assets/index.css';
const { createSliderWithTooltip } = Slider;**//Error occurs here**
const Range = createSliderWithTooltip(Slider.Range)
const Home = () => {
const [currentPage,setCurrentPage]=useState(1);
const [price,setPrice]=useState([1,1000]);
let params=useParams();
const dispatch= useDispatch();
const alert=useAlert();
const {loading,products,error,productsCount,resPerPage,filteredProductsCount }= useSelector(state=>state.products)
const keyword=params.keyword;
useEffect(() => {
if (error) {
return alert.error("error");
}
dispatch(getProducts(keyword, currentPage));
}, [dispatch, alert, error, currentPage, keyword]);
function setCurrentPageNo(pageNumber) {
setCurrentPage(pageNumber)
}
return (
<Fragment>
{loading ? <Loader>Loading ...</Loader>:(
<Fragment>
<MetaData title={'Buy Electronics , Household Items and Many Others Online'} />
<h1 id="products_heading">Latest Products</h1>
<section id="products" className="container mt-5">
<div className="row">
<Fragment>
<div className="col-6 col-md-3 mt-5 mb-5">
<div className="px-5">
<Range
marks={{
1: `$1`,
1000: `$1000`
}}
min={1}
max={1000}
defaultValue={[1, 1000]}
tipFormatter={value => `$${value}`}
tipProps={{
placement: "top",
visible: true
}}
value={price}
onChange={price => setPrice(price)}
/>
</div>
</div>
</Fragment>
{products.map(product => (
<Product key={product._id} product={product} col={4} />
))}
</div>
</section>
<div className="d-flex justify-content-center mt-5">
<Pagination
activePage={currentPage}
itemsCountPerPage={resPerPage}
totalItemsCount={productsCount}
onChange={setCurrentPageNo}//sets current page no as it changes for state management
nextPageText={'Next'}
prevPageText={'Prev'}
itemClass="page-item"
linkClass="page-link"
/>
</div>
</Fragment>
)
}
</Fragment>
)}
export default Home
Instead of const { createSliderWithTooltip } = Slider;, try this:
const createSliderWithTooltip = Slider.createSliderWithTooltip;
I tried several ways and the only thing that actually worked was downgrading to 9.6.5 rc-slider and now everything is working perfectly
The document hasn't been updated yet since new version. As it seems you want to use Range component, now here the way to do it (thanks to Ashvin-Pal): https://github.com/react-component/slider/issues/825#issuecomment-1084416952
The createSliderWithTooltip has been removed in the new version.
Instead, you can implement your custom handle or tooltip easily like this:
handleRender={renderProps => {
return (
<div {...renderProps.props}>
<SliderTooltip>{round}%</SliderTooltip>
</div>
);
}}
let me know if you have any questions.

I am am trying to link the image click to a new product page

I have created a product card to show products on my homepage. I have created and product screen to display the single product and allow the user to add to cart. When i click on the on the image the page refreshes but there is no product on the screen. I have console loged and confirmed that the property id is undefined.
import React from "react";
import { Link } from "react-router-dom";
import Rating from "./rating";
export default function Product(props) {
const { product } = props;
console.log(product._id);
return (
<div key={product._id} className="card">
<Link to={`api/products/${product._id}`}>
<img className="medium" src={product.image} alt={product.name} />
</Link>
<div className="card-body">
<Link to={`/product/${product._id}`}>
<h2>{product.name}</h2>
</Link>
<Rating
rating={product.rating}
numReviews={product.numReviews}
></Rating>
<div className="price">${product.price}</div>
</div>
</div>
);
}
``` Product component
import React from 'react'
import { Link } from 'react-router-dom';
import Rating from './rating';
import { useEffect } from 'react';
export default function Product(props) {
const { product } = props;
useEffect(()=>{
console.log('ooooh, am I undefined?');
console.log(product);
},[product]);
if(product) {
At a guess, you are passing the prop through from somewhere else into this component from some API call or async function.
What is happening, is its going from undefined to defined as part of some API call or something, and as a result, your getting undefined in your component on first render. You need to do something to keep a track of your changing state.
You'll need to do something around 'loading' state for that API call, which is outside of the component code that you've posted. In other words, your example isn't a complete picture of your code, and as such, it's hard to give you a complete answer.
Try this for debugging that assumption.
import {useState} from 'react';
export default function Product(props) {
const { product } = props;
useEffect(()=>{
console.log('ooooh, am I undefined?');
console.log(product);
},[product]);
if(product) {
return (
<div key={product._id} className="card">
<Link to=
{`api/products/${product._id}`}>
<img
className="medium"
src={product.image}
alt={product.name}
/>
</Link>
<div className="card-body">
<Link to=
{`/product/${product._id}`}>
<h2>{product.name}</h2>
</Link>
<Rating
rating={product.rating}
numReviews={product.numReviews}
></Rating>
<div
className="price">${product.price}</div>
</div>
</div>
)}
}else{
return <p>Product null</p>
}
'''
export default function HomeScreen() {
const [products, setProducts] = useState([]);
useEffect(() => {
const fecthData = async () => {
try {
const { data } = await axios.get(`https://fakestoreapi.com/products`);
setProducts(data);
} catch (err) {
console.log("Server responded with error",err);
}
};
fecthData();
}, []);
return (
<div>
<div className="row center">
{products.map((product) => (
<Product key={product._id} product={product}></Product>
))}
</div>
</div>
);
}

not able to display console data in web page

i am beginner in react . when i fetch request from API, i got data in console ,but when i am trying to display data in web page in that time data isn't show.
I want to display data in web page.
here is my console log
https://ibb.co/YLmLQz1
App.js
import React from 'react';
import './App.css';
import Header from './components/Header';
import Movie from './components/Movies';
const App = () => {
return (
<div className="App">
<Header />
<div className='container'>
<Movie />
</div>
</div>
);
}
export default App;
Header.js
In header file i created my navbar and search form
import React, { useState } from 'react'
const Header = () => {
const [search, setSearch] = useState('');
return (
<div className="jumbotron">
<h1 className="display-1">
<i className="material-icons brand-icon">LatestMovie</i> Movie
</h1>
<div className="input-group w-50 mx-auto">
<input
type="text"
className="form-control"
placeholder="Search Your Movie..."
value={search}
onChange={e => setSearch(e.target.value)}
/>
<div className="input-group-append">
<button className="btn btn-dark">
Search Movie
</button>
</div>
</div>
</div>
)
}
export default Header;
Movies.js
here i fetch my movies request throght axios
import React, { useEffect, useState } from 'react'
import Axios from 'axios';
const Movie = () => {
const [movies, setMovie] = useState([]);
const apiurl = "http://www.omdbapi.com/?apikey=642b793e&s=marvel"
const getMovies = async () => {
const res = await Axios.get(apiurl);
console.log(res);
setMovie(res.data.hits);
}
useEffect(() => {
getMovies();
}, []);
return (
<div className='row'>
{
movies && movies.map(movie => (
<div className='col-md-3'>
<div className='card'>
<div className='card-body'>
<h4>{movie.Year}</h4>
</div>
</div>
</div>
))
}
</div>
)
}
export default Movie;

Resources