React app - How to show the price when the button is clicked? - reactjs

I am just learning React and I have a problem. I want the price (cena) to appear only when the "Oblicz" button is clicked.
This is the component that shows the price.
function CalculatorPrice(props) {
const currentPrice = props.price;
return (
<div className='calculator__price'>
<CalculatorBtn />
<div className='calculator__price__box'>
<h3 className='calculator__price__title'>Cena</h3>
<p className='calculator__price__text'>{isNaN(currentPrice) ? <span></span> : <span>{currentPrice}</span>} zł</p>
</div>
</div>
);
}
This is the button component.
function CalculatorBtn() {
return (
<div>
<button className='calculateBtn'>Oblicz</button>
</div>
);
}

You can achieve that by passing state and a function to change that state to your button component which tracks when to show the price:
function CalculatorPrice(props) {
const currentPrice = props.price;
const [showPrice, setShowPrice] = useState(false);
const handleClick = () => {
setShowPrice(true);
}
return (
<div className='calculator__price'>
<CalculatorBtn showPrice={showPrice} handleClick={handleClick} />
<div className='calculator__price__box'>
<h3 className='calculator__price__title'>Cena</h3>
<p className='calculator__price__text'>
<span>{((isNaN(currentPrice) || !showPrice) ? '' : currentPrice) + zł}</span>
</p>
</div>
</div>
);
}
Button:
function CalculatorBtn(props) {
const handleClick = props.handleClick;
return (
<div>
<button className='calculateBtn' onClick={handleClick}>Oblicz</button>
</div>
);
}
You will need to add another way/button to reset your price (if you need to)

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>
)
}

How to Create Show/Hide button when Looping in React

I am working on a development site and am having an issue. The issue is that I am looping over the data file in order to create some project cards. Each project card has a show more/show less button to display/hide card descriptions.
My problem is that the current setup is mapping over the data and causing it so that whenever one gets clicked, all three either open or close simultaneously. Please help me to fix this issue. Relevant code is shown below:
Data example:
{
name: "Hot in the Biscuit",
id: "3a34",
image: "/images/bonnie.jpg",
description: "A multi-page front-end business website for a local restaurant in Koh Samui, Thailand. Custom design built with vanilla JavaScript, HTML and CSS.",
link: "https://www.xxxxxxxxxxxxx.com",
date: "2021",
github: "https://github.com/xxxxxxxxxxxxxxxxxxxxxx"
},
Hero file where Showcase Component is rendered:
<h1>Featured Projects</h1>
<div>
<Showcase/>
</div>
Showcase where cards are created (UNNECCESSARY CODE REMOVED - classes and image):
const Showcase = () => {
const {readMore, setReadMore} = useContext(HeroContext)
const {toggleMenu} = useContext(NavbarContext)
return(
<>
{showcase.map((item) => {
const {id, name, image, link, github, description, date} = item;
return (
<div key={id}>
<div>
{!toggleMenu &&
<div>
<Image/>
</div>
}
</div>
<div>
<div>
<h2>{name} | {date}</h2>
</div>
<div>
<h4>{ readMore[id] ? <-- THIS IS WHERE YOU NEED AN ID
description :
`${description.substring(0, 100)}...`
} <button key={id} onClick={() => setReadMore(!readMore)}>{readMore[id] ? "Show Less" : "Show More"}</button>
</h4>
</div>
<div>
<a href={github}>
<FiGithub/>
</a>
<a href={link}>
<h4 >See For Yourself! →</h4>
</a>
</div>
</div>
</div>
)
})}
</>
)
}
export default Showcase
So I just need some help on figuring out how to set it up so that each button knows which card is being clicked and only that button open. Thank you very much for helping me. I appreciate your time and help immensely.
Bodi
It will be easier if you split showcase item to a new component.
const ShowCaseItem = ({ data }) => {
const { toggleMenu } = useContext(NavbarContext)
const [readMore, setReadMore] = useState(false)
const { id, name, image, link, github, description, date } = data;
return (
<div key={id}>
<div>
{!toggleMenu &&
<div>
<Image />
</div>
}
</div>
<div>
<div>
<h2>{name} | {date}</h2>
</div>
<div>
<h4>{readMore ?
description :
`${description.substring(0, 100)}...`
} <button key={id} onClick={() => setReadMore(!readMore)}>{readMore ? "Show Less" : "Show More"}</button>
</h4>
</div>
<div>
<a href={github}>
<FiGithub />
</a>
<a href={link}>
<h4 >See For Yourself! →</h4>
</a>
</div>
</div>
</div>
)
}
const Showcase = () => {
const { readMore, setReadMore } = useContext(HeroContext)
return (
<>
{showcase.map((item) => <ShowCaseItem data={item} />)}
</>
)
}
export default Showcase
You should update the HeroContext state to hold a reference to the ids that are shown/hidden.
Example:
const [readMore, setReadMore] = useState({});
const readMoreToggler = (id) => setReadMore(state => ({
...state,
[id]: !state[id], // <-- toggle boolean value
}));
// context value
{
readmore,
setReadMore: readMoreToggler, // pass readMoreToggler as setReadMore
}
...
const { readMore, setReadMore } = useContext(HeroContext);
...
{showcase.map((item) => {
const {id, name, image, link, github, description, date} = item;
return (
<div key={id}>
<div>
...
</div>
<div>
...
<div>
<h4>
{readMore[id] // <-- check by id if toggled true|false
? description
: `${description.substring(0, 100)}...`
}
<button
onClick={() => setReadMore(id)} // <-- pass id to toggle
>
{readMore[id] ? "Show Less" : "Show More"} // <-- check by id if toggled true|false
</button>
</h4>
</div>
<div>
...
</div>
)
})}

React array item selection

I am trying to click on one card of a dynamically created list using map(). I want to click on one card from the array and add a class to it, while at the same time deselecting the other card that was previously clicked. How can I accomplish this? This is what I have so far:
const CardList = () => {
return (
<div className='card-list'>
{CardData.map(({ id, ...otherData }) => (
<Card key={id} {...otherData} />
))}
</div>
);
};
export default CardList;
const Card = ({
headline,
time,
views,
thumbImg,
trainerImg,
workouts,
id
}) => {
const [isSelected, setIsSelected] = useState(false);
const [clickId, setClickId] = useState('');
function handleClick(id) {
setIsSelected(!isSelected);
setClickId(id);
}
return (
<div
className={`card ${isSelected && clickId === id ? 'clicked' : ''}`}
onClick={() => handleClick(id)}
>
<div className='thumbnail-div'>
<img className='thumbnail-img' src={thumbImg} alt='video' />
{workouts ? (
<div className='workout-overlay'>
<p>{workouts}</p>
<p className='workouts'>workouts</p>
</div>
) : null}
</div>
<div className='card-info'>
<div className='card-headline'>
<p>{headline}</p>
<img src={trainerImg} alt='trainer' />
</div>
{time && views ? (
<div className='trainer-data'>
<span>
<i className='glyphicon glyphicon-time'></i>
{time}
</span>
<span>
<i className='glyphicon glyphicon-eye-open'></i>
{views}
</span>
</div>
) : null}
</div>
</div>
);
};
export default Card;
The parent component should control what card is clicked. Add className property to card component:
const Card = ({
//...
className,
onClick
}) => {
//...
return (
<div
className={`card ${className}`}
onClick={() => onClick(id)}
>...</div>
)
}
In parent component pass the className 'clicked' and add the onClick callback to set the selected card:
const CardList = () => {
const [isSelected, setIsSelected] = useState(null);
const handleClick = (id) => {
setIsSelected(id);
}
return (
<div className='card-list'>
{CardData.map(({ id, ...otherData }) => (
<Card key={id} className={isSelected===id && 'clicked'} onClick ={handleClick} {...otherData} />
))}
</div>
);
};
You can do something like this.
First you don't have to set state to each card. Instead Lift state Up.
You define which card is selected in parent so you can pass that to children and add classes if current selected is matching that children.
const CardList = () => {
const [isSelected, setIsSelected] = useState();
const handleCardClick = (id) => {
setIsSelected(id);
}
return (
<div className='card-list'>
{CardData.map(({ id, ...otherData }) => (
<Card key={id} {...otherData} handleClick={handleCardClick} isSelected={isSelected}/>
))}
</div>
);
};
export default CardList;
const Card = ({
headline,
time,
views,
thumbImg,
trainerImg,
workouts,
id,
isSelected,
handleClick
}) => {
return (
<div
className={`card ${isSelected === id ? 'clicked' : ''}`}
onClick={() => handleClick(id)}
>
<div className='thumbnail-div'>
<img className='thumbnail-img' src={thumbImg} alt='video' />
{workouts ? (
<div className='workout-overlay'>
<p>{workouts}</p>
<p className='workouts'>workouts</p>
</div>
) : null}
</div>
<div className='card-info'>
<div className='card-headline'>
<p>{headline}</p>
<img src={trainerImg} alt='trainer' />
</div>
{time && views ? (
<div className='trainer-data'>
<span>
<i className='glyphicon glyphicon-time'></i>
{time}
</span>
<span>
<i className='glyphicon glyphicon-eye-open'></i>
{views}
</span>
</div>
) : null}
</div>
</div>
);
};
export default Card;

Toggle specific div (id) within a react component

I have a site built with post-components to show articles in a feed. Inside the component, I have a button that opens a modal onClick. I use useState to toggle on the modal which works perfectly fine. The problem is that since the toggle is put on the modal-div inside the component.. every single post modal opens whenever I click one of the buttons. I want to open only the targeted post modal (with the sam post id as the button I’m clicking). I can’t figure out how to do this…in react.
const [toggle, setToggle] = useState (true);
const toggler = () => {
setToggle(prev => !prev)
}
...
return (
<section className="posts">
{data.allMarkdownRemark.edges.map((edge) => {
return (
<div className="post">
<div className="postDescrip">
<h2 className="postTitle">{edge.node.frontmatter.title}</h2>
<h2 className="name">{edge.node.frontmatter.name}</h2>
<button className="readMoreBtn" onClick={toggler}>{toggle ? <h2 className="readMore">Read more</h2> : <h2 className="readMore">Read less</h2>}
</button>
</div>
<Img className="postImg" fluid={edge.node.frontmatter.featuredImage.childImageSharp.fluid} />
<div className={toggle ? 'hide' : 'postCopy'} >
<Close close={toggler} />
<h3>{edge.node.frontmatter.details}</h3>
<div className="copy" dangerouslySetInnerHTML= {{__html: edge.node.html}}></div>
<h4>Read the full article in Issue One</h4>
</div>
</div>
)}
)}
</section>
)
}
export default Posts;
After trying suggested solution using object instead on bolean. I now receive this error message
[Error message][1]for the following code:
const [toggles, setToggles] = useState ({});
let id;
const createToggler = (id) = () => {
setToggles(prev => { [id] : !prev[id] })
// setToggle(prev => { ...prev, [id]: !prev[id] }) // or support multi modal at same time. but I think you don't want it.
}
const data = useStaticQuery(graphql`
query {
allMarkdownRemark (
sort: { order: DESC, fields: [frontmatter___date] }
){
edges {
node {
frontmatter {
id
title
name
details
featuredImage {
childImageSharp {
fluid(maxWidth: 800) {
...GatsbyImageSharpFluid
}
}
}
}
html
fields {
slug
}
}
}
}
}
`)
return (
<section className="posts">
{data.allMarkdownRemark.edges.map((edge) => {
const id = edge.node.frontmatter.id;
const toggle = toggles[id];
const toggler = createToggler(id);
return (
<div className="post" id={edge.node.frontmatter.id}>
<div className="postDescrip">
<h2 className="postTitle">{edge.node.frontmatter.title}</h2>
<h2 className="name">{edge.node.frontmatter.name}</h2>
<button className="readMoreBtn" onClick={toggler}>{toggle ? <h2 className="readMore">Read more</h2> : <h2 className="readMore">Read less</h2>}
</button>
</div>
<Img className="postImg" fluid={edge.node.frontmatter.featuredImage.childImageSharp.fluid} />
<div className={toggle ? 'hide' : 'postCopy'} id={edge.node.frontmatter.id}>
<Close close={toggler} />
<h3>{edge.node.frontmatter.details}</h3>
<div className="copy" dangerouslySetInnerHTML= {{__html: edge.node.html}}></div>
<h4>Read the full article in Issue One</h4>
</div>
</div>
)}
)}
</section>
)
}
export default Posts;
[1]: https://i.stack.imgur.com/VhIYF.png
like this.
use a object instead of a single boolean.
const [toggles, setToggles] = useState ({});
const createToggler = (id) = () => {
setToggle(prev => { [id]: !prev[id] }) // atmost one id is true. others is undefine or false.
// setToggle(prev => { ...prev, [id]: !prev[id] }) // or support multi modal at same time. but I think you don't want it.
}
...
return (
<section className="posts">
{data.allMarkdownRemark.edges.map((edge) => {
const id = ... // get your id form edge.
const toggle = toggles[id];
const toggler = createToggler(id);
return (
<div className="post">
<div className="postDescrip">
<h2 className="postTitle">{edge.node.frontmatter.title}</h2>
<h2 className="name">{edge.node.frontmatter.name}</h2>
<button className="readMoreBtn" onClick={toggler}>{toggle ? <h2 className="readMore">Read more</h2> : <h2 className="readMore">Read less</h2>}
</button>
</div>
<Img className="postImg" fluid={edge.node.frontmatter.featuredImage.childImageSharp.fluid} />
<div className={toggle ? 'hide' : 'postCopy'} >
<Close close={toggler} />
<h3>{edge.node.frontmatter.details}</h3>
<div className="copy" dangerouslySetInnerHTML= {{__html: edge.node.html}}></div>
<h4>Read the full article in Issue One</h4>
</div>
</div>
)}
)}
</section>
)
}
export default Posts;
I solved my problem like this
import React, {useState} from "react"
import Img from "gatsby-image"
import './posts.css';
import cancel from '../images/cancel.png'
const Post = ({title, name, id, image, details, html}) => {
const [toggle, setToggle] = useState (true);
const toggler = () => {
setToggle(prev => !prev)
}
const selectPost= (event) =>{
let id = event.target.id,
postCopy = document.getElementById('hide' + id);
toggler.call(postCopy);
}
return (
<div className="post">
<div className="postDescrip">
<h2 className="postTitle">{title}</h2>
<h2 className="name">{name}</h2>
<button className="readMoreBtn" onClick={selectPost}>{toggle ? <h2 id={id} className="readMore">Read more</h2> : <h2 id={id} className="readMore">Read less</h2>}
</button>
</div>
<Img className="postImg" fluid={image} />
<div id={'hide' + id} className={toggle ? 'hide' : 'postCopy'} >
<button aria-label="Close" onClick={selectPost} className="closeBtn">
<img alt="close-button" src={cancel}/>
</button>
<h3>{details}</h3>
<div className="copy" dangerouslySetInnerHTML= {html}></div>
<h4>Read the full article in Issue One</h4>
</div>
</div>
)
}
export default Post;

Force update to make functional component re-render

I'm doing pokedex (pokemon wiki stuff). I want to change my component view, when clicking on pokemon images (description lookalike). When I click on an image - nothing happens (firstly, I want at least pokemon's name to be added to the pokemonDescription array). What am I doing wrong?
let pokemonDescription = [];
const useForceUpdate = () => {
const [value, setValue] = useState(true);
return () => setValue(value => !value);
}
const forceUpdate = useForceUpdate();
const onPokemonClick = (event) => {
console.log(
"wrapper clicked, event.target - ",
event.target.getAttribute('data-name')
);
pokemonDescription = [];
pokemonDescription.push(event.target.getAttribute('data-name'));
console.log("description array -", pokemonDescription);
forceUpdate();
};
useEffect(() => {
document.querySelector(".wrapper").addEventListener("click", onPokemonClick);
...
return () => {
document.querySelector(".wrapper").removeEventListener("click", onPokemonClick);
};
}, []);
...
return (
<div className="Pokemons">
<div className="column pokemons-list">
<div className="wrapper">
{
pokemonsData.map((p, id) => (
<div className="box" key={ id }>
<img
src={ p.sprites.front_default }
alt="pokemon-img"
title={ p.name }
className="icon"
data-name={p.name}
/>
{ p.name}
<div className="container">
{ pokemonsTypes[id] }
</div>
</div>
))
}
</div>
...
</div>
<div className="column description">
{ pokemonDescription }
</div>
</div>
)
You should add pokemonDescription to your component state
const [pokemonDescription, setPokemonDescription] = useState([]);
Remove the forceUpdate function and hook, it is unnecessary.
Attach the click handlers to the elements with the data-name attribute you are trying to handle.
Map the pokemonDescription state array to renderable JSX. I simply used a div, but you should use whatever your UI design requires.
const onPokemonClick = (event) => {
setPokemonDescription(names => [
...names,
event.target.getAttribute('data-name'),
]);
};
...
return (
<div className="Pokemons">
<div className="column pokemons-list">
<div className="wrapper">
{
pokemonsData.map((p, id) => (
<div className="box" key={ id }>
<img
src={ p.sprites.front_default }
alt="pokemon-img"
title={ p.name }
className="icon"
data-name={p.name}
onClick={onPokemonClick} // <-- attach click handler to img element
/>
{ p.name}
<div className="container">
{ pokemonsTypes[id] }
</div>
</div>
))
}
</div>
...
</div>
<div className="column description">
{pokemonDescription.map(name => (
<div>{name}</div>
))}
</div>
</div>
)
Add pokemonDescription to state instead of some local variable and it will solve your issue.
Try to avoid using forceUpdate, most of the times it means only that you are doing something silly.
I don't what that useForceUpdate does , but here is how would go about adding pokemon names to description array which is a state variable in my answer
const [pokemonDescription , setPokemonDescription ] = useState(null);
const onPokemonClick = (p) => {
const tempPokemonDescription = [...pokemonDescription ];
pokemonDescription.push(p.name);
console.log("description array -", pokemonDescription);
setPokemonDescription(tempPokemonDescription )
};
...
return (
<div className="Pokemons">
<div className="column pokemons-list">
<div className="wrapper">
{
pokemonsData.map((p, id) => (
<div className="box" onClick={e=>onPokemonClick(p)} key={ id }>
<img
src={ p.sprites.front_default }
alt="pokemon-img"
title={ p.name }
className="icon"
/>
{ p.name}
<div className="container">
{ pokemonsTypes[id] }
</div>
</div>
))
}
</div>
...
</div>
<div className="column description">
{ pokemonDescription }
</div>
</div>
)

Resources