why cannot I see my modal when I increased number? - reactjs

Can you please show me why my Modal is not show up when I increased number?
Counting is working but Modal is not working.
I want to show Modal when I increase number. Thank you
function App() {
const [count, setCoutn] = useState(0)
const [showModal, setShowModal] = useState(false)
const increase = () => {
setCoutn(count + 1)
setShowModal(true)
}
return (
<>
{ showModal && < Modal /> }
<p className="text-center mt-5 mt-5 fs-5 count">{count}</p>
<div className="btn-box">
<button className="btn btn-outline-primary" onClick={()=>increase()}>increase</button>
</div>
</>
);
}
const Modal = () => {
return (
<div>
<p className='modal'>Modal</p>
</div>
)
}

Check your demo
instead of :
onClick={()=>increase()}
But I recommend using:
onClick={increase}
Because it will call the function increase directly when clicking the button.

**You cant see modal,because showModal is false default!**
function App() {
const [count, setCoutn] = useState(0)
const [showModal, setShowModal] = useState(false)
const increase = () => {
setCoutn(count + 1)
setShowModal(true)
}
if(showModal) {
return (
<>
<p className="text-center mt-5 mt-5 fs-5 count">{count}</p>
<div className="btn-box">
<button className="btn btn-outline-primary" onClick={()=>increase()}>increase</button>
</div>
</>
);
}else{
return (
<div>
<p className='modal'>Modal</p>
</div>
)
}
}

Related

How can I only open one popup at a time based on a map function in react?

I am making a movie dashboard where users can search for movies and save them to their watch list. I am trying to have a popup containing the movie information that will appear if the user clicks on the image card for each movie. This is kind of working, but the problem is that the popup shows for every movie when I only click on one. My code is shown before. I haven't styled the popup yet, but the information looks right for each movie. Thanks for your help!
function Watchlist() {
const { watchlist } = useContext(GlobalContext);
const [modal, setModal] = useState(false);
const toggleModal = () => {
setModal(!modal);
}
return (
<div className='watchlist'>
<h1 className='title'>your watchlist</h1>
{watchlist.length > 0 ? (
<div className="movies">
{watchlist.map((movie, index) => {
if(index % 3 === 1) {
return (
<div className="movie-wrapper">
<button name={movie.id} className="open-modal" onClick={toggleModal} key={movie.id}>
<Card img={`https://image.tmdb.org/t/p/w200${movie.poster_path}`} margin={30} key={movie.id}/>
</button>
{modal && (
<div className="movie-details">
<div className="modal-content">
<ResultCard movie={movie} key={movie.id}/>
<button className="close-modal" onClick={toggleModal}>X</button>
</div>
</div>
)}
</div>
)
} else {
<div className="movie-wrapper">
<button name={movie.id} className="open-modal" onClick={toggleModal} key={movie.id}>
<Card img={`https://image.tmdb.org/t/p/w200${movie.poster_path}`} margin={0} key={movie.id}/>
</button>
{modal && (
<div className="movie-details">
<div className="modal-content">
<ResultCard movie={movie} key={movie.id}/>
<button className="close-modal" onClick={toggleModal}>X</button>
</div>
</div>
)}
</div>
}
})}
</div>
) : (
<h2 className="no-movies">Add some movies!</h2>
)}
</div>
)
}
You need to keep the movie id you want to show the modal for:
const [modal, setModal] = useState(false);
const [selectedMovie, setSelectedMovie] = useState();
const toggleModal = (movieId) => {
setModal(!modal);
setSelectedMovie(movieId)
}
onClick={() => toggleModal(movie.id)}
and check the selected movie when rendering:
{modal && movie.id === selectedMovie && (...
It's because you are rendering a modal for each movie in your list.
Take the modal out of the map function, and keep it as a child of the component where it does not rely on any condition, any mapped list, or anything else for it to be rendered. It's kind of a convention (at least among the codebases I've come across) to put modals at the end of the component JSX, as a direct child of the root element of the component.
Hide it by default, and only show it when a user clicks on a movie, passing the relevant info into the modal.
It might look something like this:
function Watchlist() {
const { watchlist } = useContext(GlobalContext);
const [modal, setModal] = useState(false);
const [selectedMovie, setSelectedMovie] = useState({});
const toggleModal = () => {
setModal(!modal);
}
return (
<div className='watchlist'>
<h1 className='title'>your watchlist</h1>
{watchlist.length > 0 ? (
<div className="movies">
{watchlist.map((movie, index) => {
// Render the mapped list of JSX elements (movie cards?)
// Potentially the `onClick` event would trigger the `setSelectedMovie` function in addition to setting `toggleModal`
})}
</div>
) : (
<h2 className="no-movies">Add some movies!</h2>
)}
{modal && (
<div className="movie-details">
<div className="modal-content">
<ResultCard movie={selectedMovie} key={selectedMovie.id}/>
<button className="close-modal" onClick={toggleModal}>X</button>
</div>
</div>
)}
</div>
)
}

Conditional rendering JSX

I have some lines of JSX that I want to show/hide when I click on a button.
I have initialized the state as such :
const [shown, setShown] = useState(true);
And this is the JSX :
<div className="question--section">
<div className="question--count">
<span>Question {props.class[currentQuestion].id} </span>
<h1>{props.class[currentQuestion].questionText}</h1>
</div>
</div>
I have tried to to do this :
{shown ? (
<div className="question--section">
<div className="question--count">
<span>Question {props.class[currentQuestion].id} </span>
<h1>{props.class[currentQuestion].questionText}</h1>
</div>
</div>) :
(<div>Empty</div>)}
It doesn't work. How should I approach this? ( Switching the state should hide/show the JSX)
The whole component :
import React from "react";
import { useState } from "react";
const Quiz = (props) => {
const [currentQuestion, setCurrentQuestion] = useState(0);
const [shown, setShown] = useState(true);
const handleAnswerButtonClick = () => {
if (currentQuestion + 1 < props.class.length) {
setCurrentQuestion((prevQuestion) => prevQuestion + 1);
} else {
alert("End of the quiz!");
}
};
return (
<div className="container quiz--container">
<button>Κεφάλαιο 1</button>
{shown ? (
<div>
<h1>Κεφάλαιο {props.id}</h1>
<div className="question--section">
<div className="question--count">
<span>Question {props.class[currentQuestion].id} </span>
<h1>{props.class[currentQuestion].questionText}</h1>
</div>
</div>
<div className="answer-section">
{props.class[currentQuestion].answers.map((answer) => (
<button onClick={handleAnswerButtonClick}>{answer.answerText}</button>
))}
</div>) :
(<div>Empty</div>)}
</div>
);
};
export default Quiz;
You are missing a closing </div> before the :.
It should be this:
<div className="container quiz--container">
<button>Κεφάλαιο 1</button>
{shown ? (
<div>
<h1>Κεφάλαιο {props.id}</h1>
<div className="question--section">
<div className="question--count">
<span>Question {props.class[currentQuestion].id} </span>
<h1>{props.class[currentQuestion].questionText}</h1>
</div>
</div>
<div className="answer-section">
{props.class[currentQuestion].answers.map((answer) => (
<button onClick={handleAnswerButtonClick}>{answer.answerText}</button>
))}
</div>
</div>) :
(<div>Empty</div>)}
</div>
Inside handleAnswerButtonClick callback, setShown to false or reverse it.
const handleAnswerButtonClick = () => {
setShown(false)
// or
setShown(!shown)
...
}

State returning undefined in typescript

I'm trying to change the state of a component with data from an external api. The state is to add a component as a favourite, but returns undefined. I'm already using arrow functions and the .bind() didn't work as well. What am I missing here?
Library Component:
export default function LibraryComponent() {
const [albums, setAlbums] = useState<any[]>([]);
const [albumTitle, setAlbumTitle] = useState<any[]>([]);
const [photoUrl, setPhotoUrl] = useState();
const [favourite, setFavourite] = useState<any[]>([]);
//FETCH DATA
const fetchData = () => {
const getAlbums = "https://jsonplaceholder.typicode.com/albums?_limit=20";
const getPhotos =
"https://627ed423b75a25d3f3bd811f.mockapi.io/api/photos/1"; //random number here
const albums = axios.get(getAlbums).then((res) => {
setAlbums(res.data);
});
const photoUrl = axios.get(getPhotos).then((res) => {
setPhotoUrl(res.data.images);
});
};
const addFavourite = (album: []) => {
const favouriteList = [...favourite, album];
setFavourite(favouriteList);
};
return (
<>
<div className="container-fluid w-50">
<div className="row">
{albums.map((album) => (
<div key={album.id} className="col-lg-2 col-sm-6">
<div className="col-lg-12 col-sm-6">
<div className="thumbnail img-responsive">
<AlbumComponent
title={album.title}
image={photoUrl}
handleFavouriteClick={addFavourite}
/>
</div>
</div>
</div>
))}
</div>
</div>
</>
);
}
Album Component:
type Meta = {
title: any;
image: any;
handleFavouriteClick: any;
};
export default function AlbumComponent(props: Meta) {
return (
<>
<img src={props.image} alt="" className="img-fluid img-thumbnail" />
<p>{props.title}</p>
<div onClick={() => props.handleFavouriteClick()}>
<i className="fa-regular fa-heart"></i>
</div>
</>
);
}
addFavourite expects an album parameter.
Try something like this:
<AlbumComponent
title={album.title}
image={photoUrl}
handleFavouriteClick={() => addFavourite(album)}
/>
You need to pull the value from the input and provide it as a parameter to the function. You could use a controlled input for this. Somehting like this:
export default function AlbumComponent(props: Meta) {
const [value, setValue] = React.useState()
return (
<>
<img src={props.image} alt="" className="img-fluid img-thumbnail" />
<p>{props.title}</p>
<div onClick={() => props.handleFavouriteClick(value)}>
<i className="fa-regular fa-heart" value={value} onChange={setValue}></i>
</div>
</>
);
}

Use State not updating as expected

Fairly new to react and trying to build a clone of The Movie Database site. I want this toggle switch to change my api call from movies to tv. It starts working after a couple clicks, but then it throws everything off and it's not displaying the correct items anyway. Not really sure what's going on here...or even why it starts working after two clicks. Anyone know whats up with this?
import React, { useState, useEffect } from "react";
import axios from "axios";
import API_KEY from "../../config";
const Popular = ({ imageUri }) => {
// GET POPULAR MOVIES
const [popularMovies, setPopularMovies] = useState("");
const [genre, setGenre] = useState("movie");
console.log(genre);
const getPopular = async () => {
const response = await axios.get(
`https://api.themoviedb.org/3/discover/${genre}?sort_by=popularity.desc&api_key=${API_KEY}`
);
setPopularMovies(response.data.results);
};
useEffect(() => {
getPopular();
}, []);
const listOptions = document.querySelectorAll(".switch--option");
const background = document.querySelector(".background");
const changeOption = (el) => {
let getGenre = el.target.dataset.genre;
setGenre(getGenre);
getPopular();
listOptions.forEach((option) => {
option.classList.remove("selected");
});
el = el.target.parentElement.parentElement;
let getStartingLeft = Math.floor(
listOptions[0].getBoundingClientRect().left
);
let getLeft = Math.floor(el.getBoundingClientRect().left);
let getWidth = Math.floor(el.getBoundingClientRect().width);
let leftPos = getLeft - getStartingLeft;
background.setAttribute(
"style",
`left: ${leftPos}px; width: ${getWidth}px`
);
el.classList.add("selected");
};
return (
<section className="container movie-list">
<div className="flex">
<div className="movie-list__header">
<h3>What's Popular</h3>
</div>
<div className="switch flex">
<div className="switch--option selected">
<h3>
<a
data-genre="movie"
onClick={(e) => changeOption(e)}
className="switch--anchor"
>
In Theaters
</a>
</h3>
<div className="background"></div>
</div>
<div className="switch--option">
<h3>
<a
data-genre="tv"
onClick={(e) => changeOption(e)}
className="switch--anchor"
>
On TV
</a>
</h3>
</div>
</div>
</div>
<div className="scroller">
<div className="flex flex--justify-center">
<div className="flex flex--nowrap container u-overScroll">
{popularMovies &&
popularMovies.map((movie, idX) => (
<div key={idX} className="card">
<div className="image">
<img src={imageUri + "w500" + movie.poster_path} />
</div>
<p>{movie.title}</p>
</div>
))}
</div>
</div>
</div>
</section>
);
};
export default Popular;
You're using the array index as your key prop when you're mapping your array.
You should use an id that is specific to the data that you're rendering.
React uses the key prop to know which items have changed since the last render.
In your case you should use the movie id in your key prop instead of the array index.
popularMovies.map((movie) => (
<div key={movie.id} className="card">
<div className="image">
<img src={imageUri + 'w500' + movie.poster_path} />
</div>
<p>{movie.title}</p>
</div>
));
Also
You're calling the api directly after setGenre. However state changes aren't immediate. So when you're making your api call you're still sending the last movie genre.
Two ways of fixing this:
You could call your function with the genre directly, and change your function so it handles this case:
getPopular('movie');
Or you could not call the function at all and add genre as a dependency of your useEffect. That way the useEffect will run each time the genre change.
useEffect(() => {
getPopular();
}, [genre]);
PS: You should consider splitting your code into more component and not interacting with the DOM directly.
To give you an idea of what it could look like, I refactored a bit, but more improvements could be made:
const Popular = ({ imageUri }) => {
const [popularMovies, setPopularMovies] = useState('');
const [genre, setGenre] = useState('movie');
const getPopular = async (movieGenre) => {
const response = await axios.get(
`https://api.themoviedb.org/3/discover/${movieGenre}?sort_by=popularity.desc&api_key=${API_KEY}`
);
setPopularMovies(response.data.results);
};
useEffect(() => {
getPopular();
}, [genre]);
const changeHandler = (el) => {
let getGenre = el.target.dataset.genre;
setGenre(getGenre);
};
const isMovieSelected = genre === 'movie';
const isTvSelected = genre === 'tv';
return (
<section className="container movie-list">
<div className="flex">
<MovieHeader>What's Popular</MovieHeader>
<div className="switch flex">
<Toggle onChange={changeHandler} selected={isMovieSelected}>
In Theaters
</Toggle>
<Toggle onChange={changeHandler} selected={isTvSelected}>
On TV
</Toggle>
</div>
</div>
<div className="scroller">
<div className="flex flex--justify-center">
<div className="flex flex--nowrap container u-overScroll">
{popularMovies.map((movie) => {
const { title, id, poster_path } = movie;
return (
<MovieItem
title={title}
imageUri={imageUri}
key={id}
poster_path={poster_path}
/>
);
})}
</div>
</div>
</div>
</section>
);
};
export default Popular;
const Toggle = (props) => {
const { children, onChange, selected } = props;
const className = selected ? 'switch--option selected' : 'switch--option';
return (
<div className={className}>
<h3>
<a
data-genre="movie"
onClick={onChange}
className="switch--anchor"
>
{children}
</a>
</h3>
<div className="background"></div>
</div>
);
};
const MovieHeader = (props) => {
const { children } = props;
return (
<div className="movie-list__header">
<h3>{children}</h3>
</div>
);
};
const MovieItem = (props) => {
const { title, imageUri, poster_path } = props;
return (
<div key={idX} className="card">
<div className="image">
<img src={imageUri + 'w500' + poster_path} />
</div>
<p>{title}</p>
</div>
);
};

Why is my fetched data not appearing in my React hooks component?

I am trying to load data into my component for it to be displayed. I thought the issue was that I wasn't using async/await for the fetch, but even after adding that it still is not loading. I am logging out the "offerings" and it is just showing the empty array. How do I keep the component from rendering until after the data is loaded??
Thanks in advance!
const [offerings, setOfferings] = useState([]);
const loadData = async () => {
const res = await fetch(`http://52.207.83.69` + `${CRUD_OFFERING}`);
setOfferings(await res.json());
console.log(offerings, 'offerings')
};
useEffect(async () => {
navbarToggle();
await loadData();
}, []);
const dispatch = useDispatch();
const modalState = useSelector((state) => state.modal);
const modalToggle = () => {
dispatch({
type: MODAL_TOGGLE,
payload: !modalState.show,
});
ga.event("navbar_requestdemo_clicked");
};
const navbarOpenState = useSelector((state) => state.navbar);
const navbarToggle = () => {
if (!navbarOpenState.open) return;
dispatch({
type: NAVBAR_OPEN,
payload: false,
});
};
return (
<div
className="d-flex justify-content-center align-items-center bg-color-white fc-px-15"
onClick={navbarToggle}
>
<div className={homeStyles["padded-body"] + " col-11 p-0"}>
<div className=" position-relative bg-color-white">
<div className={homeStyles["img-holder"]}></div>
<div className="col-12 column position-absolute top-0 d-flex justify-content-center">
<div className="col-lg-6 col-12 fc-mt-2">
<SearchBar />
</div>
</div>
<div className="position-absolute top-50 translateY-middle">
<div className="position-relative">
<h1 className={`${homeStyles["hero-text"]} font-weight-bolder`}>
Building
<br />
Meaningful
<br />
Engagement
</h1>
<button
className="btn btn-primary-round mt-3 px-3 py-2"
onClick={() => {
modalToggle();
}}
>
Request access
</button>
</div>
</div>
</div>
<div
id={homeStyles["discover-section"]}
className="d-flex justify-content-center align-items-center"
>
<div className="col-12 column">
<h4 className="font-weight-bold">Discover</h4>
<div
id={homeStyles["offer-section"]}
className="row justify-content-center align-items-center"
>
{!offerings?.length &&
<h4 className="text-center">There are no active offerings.</h4>
}
</div>
<OfferingCarousal
offeringsList={offerings}
name={"Offerings"}
/>
<div id={homeStyles["consultancy-section"]} className="">
<div className="row">
<div
className="d-flex justify-content-center align-items-center col-lg-6 col-12 px-0 mt-3 mb-4"
id={homeStyles["consultancy-div"]}
>
<div className="col-12 column p-5">
<h1 className="font-weight-bold">Add your consultancy</h1>
<h5 className="mt-4">
Reach more people and organizations
</h5>
<Link href="/consultancies">
<button className="btn btn-primary-round mt-4">
Learn more
</button>
</Link>
</div>
</div>
<div className="col-lg-6 col-12 px-0">
<img
src="/images/Rachael_glasses_home_page.jpg"
id={homeStyles["consultant-img"]}
className="mt-3"
/>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
};
export default HomeNew;
You can check if the data is present before you consume the data.
const [offerings, setOfferings] = useState([]);
const loadData = async () => {
const res = await fetch(`http://52.207.83.69` + `${CRUD_OFFERING}`);
setOfferings(res.json());
console.log(res, 'offerings')
};
useEffect(() => {
navbarToggle();
loadData(); // await has no affect inside useEffect for top level functions
}, []);
// removed internal code for clarity
const dispatch = useDispatch(...yourCode);
const modalState = useSelector(...yourCode);
const modalToggle = () => {...yourCode};
const navbarOpenState = useSelector(...yourCode);
const navbarToggle = () => {...yourCode};
// check after the hooks and before the consuming the data
if(!offerings && !offerings.length) return <>No offerings</>;
return <div>your side nav</div>;
};
It's also good practice to catch asynchronous errors as they occur to prevent your a single component form breaking your whole app. You can also take advantage of the try...catch and put in loading and error states too.
const [loading, setLoading] = useState(false);
const [error, setError] = useState(false);
const [offerings, setOfferings] = useState([]);
const loadData = async () => {
try {
setError(false);
setLoading(true);
const res = await fetch(`http://52.207.83.69` + `${CRUD_OFFERING}`);
setOfferings(res.json());
} catch (e){
setError(true)
} finally {
setLoading(false);
}
};
// other code from above
if(error) return <>error</>;
if(loading) return <>loading</>;
if(!offerings && !offerings.length) return <>No offerings</>;
return <div>your side nav</div>;
};
async function can't be put in the useEffect hook directly.
https://prnt.sc/1lu7vdc
It can be like this.
useEffect(() => {
...
(async ()=>{
await loadData()
})();
}, []);
But in your case, I think you don't need to wait until loadData function is executed.
Just make sure you handle exceptions on the rendering for Empty data.

Resources