I made this function in React that allows users to click one of 5 stars and it visually shows how many stars were "selected" (a 5-star rating system).
This function is in its own .js file in a React app, and it returns a div element that is rendered in a different .js file.
My problem is that I want to display how many stars the user clicked (ex. 3 out of 5 stars), but I don't know how to get that information from the .js file with the function to the other .js file where the div element is rendered.
Any help would be much appreciated!
import React, { useState } from "react";
const StarRating = () => {
const [rating, setRating] = useState(0);
const [hover, setHover] = useState(0);
return (
<div className="star-rating">
{[...Array(5)].map((star, index) => {
index += 1;
return (
<button class="star"
type="button"
key={index}
className={index <= (hover || rating) ? "on" : "off"}
onClick={() => setRating(index)}
onMouseEnter={() => setHover(index)}
onMouseLeave={() => setHover(rating)}
>
<span className="star">⚇</span>
</button>
);
})}
</div>
);
};
export default StarRating;
Related
For example I have this code.
And I want to use CSS transitionfor Button when showButton and when !showButton. Now it's just removed and add Button when showButton changes.
{showButton && (
<Button
onClick={() => setShowMessage(true)}
size="lg"
>
Show Message
</Button>
)}
Is it possible make by some events or appending classNames like active?
Append the className with the ternary operator.
But, for example, this code will only adjust the class of the button specified (effectively doing the same thing you described, hiding & showing the button):
import React, { useState } from 'react';
export const Component = () => {
const [showButton, setShowButton] = useState(false);
const handleClick = () => {
setShowButton(true);
}
return (
<button
onClick={handleClick}
className={showButton ? 'showButtonClass' : 'hideButtonClass'}
>
Show Message
</button>
);
};
For content to show once the button is clicked, you'll need something like:
import React, { useState } from 'react';
export const Component = () => {
const [showMessage, setShowMessage] = useState(false);
const handleClick = () => {
setShowMessage(true);
}
return (
<div>
<button
onClick={handleClick}
>
Show Message
</button>
{showMessage && <h1>
The message you'll see when clicking!
</h1>}
</div>
);
};
I am trying to create a system where I can easily click a given sentence on the page and have it toggle to a different sentence with a different color upon click. I am new to react native and trying to figure out the best way to handle it. So far I have been able to get a toggle working but having trouble figuring out how to change the class as everything is getting handled within a single div.
const ButtonExample = () => {
const [status, setStatus] = useState(false);
return (
<div className="textline" onClick={() => setStatus(!status)}>
{`${status ? 'state 1' : 'state 2'}`}
</div>
);
};
How can I make state 1 and state 2 into separate return statements that return separate texts + classes but toggle back and forth?
you can just create a component for it, create a state to track of toggle state and receive style of text as prop
in React code sandbox : https://codesandbox.io/s/confident-rain-e4zyd?file=/src/App.js
import React, { useState } from "react";
import "./styles.css";
export default function ToggleText({ text1, text2, className1, className2 }) {
const [state, toggle] = useState(true);
const className = `initial-style ${state ? className1 : className2}`;
return (
<div className={className} onClick={() => toggle(!state)}>
{state ? text1 : text2}
</div>
);
}
in React-Native codesandbox : https://codesandbox.io/s/eloquent-cerf-k3eb0?file=/src/ToggleText.js:0-465
import React, { useState } from "react";
import { Text, View } from "react-native";
import styles from "./style";
export default function ToggleText({ text1, text2, style1, style2 }) {
const [state, toggle] = useState(true);
return (
<View style={styles.container}>
<Text
style={[styles.initialTextStyle, state ? style1 : style2]}
onPress={() => toggle(!state)}
>
{state ? text1 : text2}
</Text>
</View>
);
}
This should be something you're looking for:
import React from "react"
const Sentence = ({ className, displayValue, setStatus }) => {
return (
<div
className={className}
onClick={() => setStatus((prevState) => !prevState)}
>
{displayValue}
</div>
);
};
const ButtonExample = () => {
const [status, setStatus] = React.useState(false);
return status ? (
<Sentence
className="textLine"
displayValue="state 1"
setStatus={setStatus}
/>
) : (
<Sentence
className="textLineTwo"
displayValue="state 2"
setStatus={setStatus}
/>
);
};
You have a Sentence component that takes in three props. One for a different className, one for a different value to be displayed and each will need access to the function that will be changing the status state. Each setter from a hook also has access to a function call, where you can get the previous (current) state value, so you don't need to pass in the current state value.
Sandbox
I am a Beginner to Reactjs and I just started working on a Tinder Clone with swipe functionality using tinde-card-react.
I am trying to get two variables to update using React useState() but coudn't.
There are 2 main components inside the main function, a TinderCards component and Swipe right and left and Replay buttons. The problem is that when I swipe the cards manually variables don't get updated and this is not the case when i swipe using the buttons.
In the current log, I swiped the cards twice to the right and logged the variables alreadyRemoved and people. The variable people is initially an Array containing 3 objects so after the second swipe it's supposed to log only 2 objects not 3, While the alreadyRemoved variable is supposed to update to the missing elements of the variable people.
This is my code :
import React, { useState, useEffect, useMemo } from 'react';
import './IslamCards.css';
import Cards from 'react-tinder-card';
import database from './firebase';
import hate from "./Cross.png"
import replayb from "./Replay.png"
import love from "./Love.png"
import IconButton from "#material-ui/core/IconButton"
function IslamCards(props) {
let [people, setPeople] = useState([])
useEffect(() => {
database.collection("People").onSnapshot(snapshot => { setPeople(snapshot.docs.map(doc => doc.data())) })
}, [])
let [alreadyRemoved , setalreadyRemoved] = useState([])
let buttonClicked = "not clicked"
// This fixes issues with updating characters state forcing it to use the current state and not the state that was active when the card was created.
let childRefs = useMemo(() => Array(people.length).fill(0).map(() => React.createRef()), [people.length])
let swiped = () => {
if(buttonClicked!=="clicked"){
console.log("swiped but not clicked")
if(people.length){
let cardsLeft = people.filter(person => !alreadyRemoved.includes(person))
if (cardsLeft.length) {
let toBeRemoved = cardsLeft[cardsLeft.length - 1] // Find the card object to be removed
let index = people.map(person => person.name).indexOf(toBeRemoved.name)// Find the index of which to make the reference to
setalreadyRemoved(list => [...list, toBeRemoved])
setPeople(people.filter((_, personIndex) => personIndex !== index))
console.log(people)
console.log(alreadyRemoved)
}
}
buttonClicked="not clicked"
}
}
let swipe = (dir) => {
buttonClicked="clicked"
console.log("clicked but not swiped")
if(people.length){
let cardsLeft = people.filter(person => !alreadyRemoved.includes(person))
if (cardsLeft.length) {
let toBeRemoved = cardsLeft[cardsLeft.length - 1] // Find the card object to be removed
let index = people.map(person => person.name).indexOf(toBeRemoved.name)// Find the index of which to make the reference to
setalreadyRemoved(list => [...list, toBeRemoved])
childRefs[index].current.swipe(dir)
let timer =setTimeout(function () {
setPeople(people.filter((_, personIndex) => personIndex !== index))}
, 1000)
console.log(people)
console.log(alreadyRemoved)
}
// Swipe the card!
}
}
let replay = () => {
let cardsremoved = alreadyRemoved
console.log(cardsremoved)
if (cardsremoved.length) {
let toBeReset = cardsremoved[cardsremoved.length - 1] // Find the card object to be reset
console.log(toBeReset)
setalreadyRemoved(alreadyRemoved.filter((_, personIndex) => personIndex !== (alreadyRemoved.length-1)))
if (!alreadyRemoved.length===0){ alreadyRemoved=[]}
let newPeople = people.concat(toBeReset)
setPeople(newPeople)
// Make sure the next card gets removed next time if this card do not have time to exit the screen
}
}
return (
<div>
<div className="cardContainer">
{people.map((person, index) => {
return (
<Cards ref={childRefs[index]} onSwipe={swiped} className="swipe" key={index} preventSwipe={['up', 'down']}>
<div style={{ backgroundImage: `url(${person.url})` }} className="Cards">
<h3>{person.name}</h3>
</div>
</Cards>);
})}
</div>
<div className="reactionButtons">
<IconButton onClick={() => swipe('left')}>
<img id="hateButton" alt="d" src={hate} style={{ width: "10vh", marginBottom: "5vh", pointerEvents: "all" }} />
</IconButton>
<IconButton onClick={() => replay()}>
<img id="replayButton" alt="e" src={replayb} style={{ width: "11vh", marginBottom: "5vh", pointerEvents: "all" }} />
</IconButton>
<IconButton onClick={() => swipe('right')}>
<img id="loveButton" alt="f" src={love} style={{ width: "11vh", marginBottom: "5vh", pointerEvents: "all" }} />
</IconButton>
</div>
</div>
);
}
export default IslamCards;
My console Log :
UPDATE :
As suggested in the 1st answer, I removed the Timer from the swiped() function but the problem persisted.
I hope to get more suggestions, so that I can solve this problem.
I can see the problem, but you might need to figure out what to do after that.
setPeople(people.filter((_, personIndex) => personIndex !== index))}
, 1000)
The problem is that index is figured out from the current update, however it takes 1 second to reach the next update, in between, your index points to the same one, because your index is derived from the people.
I have two cards now when I hover on one card it triggers in all two cards on hover (onMouseEnter)
Here is the solutions I have
import React, { useState } from "react";
const Buttons = () => {
const [isShown, setIsShown] = useState(false);
return (
<div>
<div
onMouseEnter={() => setIsShown(true)}
onMouseLeave={() => setIsShown(false)}
className="wrapper-btn"
>
{isShown && <button> test 1 </button>}
</div>
<div
onMouseEnter={() => setIsShown(true)}
onMouseLeave={() => setIsShown(false)}
className="wrapper-btn"
>
{isShown && <button> test 2 </button>}
</div>
</div>
);
};
export default Buttons;
What is wrong here?
both share the same state, you can abstract your code to another component where each one has an independent state:
import React, { useState } from "react";
const Buttons = () => {
return (
<div>
<ButtonDisplay btnContent='test 1' />
<ButtonDisplay btnContent='test 2' />
</div>
);
};
export default Buttons;
const ButtonDisplay = ({ btnContent }) => {
const [isShown, setIsShown] = useState(false);
return (
<div
onMouseEnter={() => setIsShown(true)}
onMouseLeave={() => setIsShown(false)}
className="wrapper-btn"
>
{isShown && <button> { btnContent } </button>}
</div>
)}
this would be the approach I would take since keeps your code dry.
other approach possible would change isShown state to an array that tracks each button isShown state, where onMouseEnter|Leave would update a specific index of that array and also read from that one, hence you would render your button based on specific value from an index of your state. or you could create a state to each button which would be the least optimal when you have multiple buttons.
I have cards and modals, I need to only show 2 cards in the page and have a button to show the rest, I’m new in programming and react, I don’t know what I have to do, that’s what I have now,
import React from "react"
import { Container } from "./_styles"
import { useTheme } from "#material-ui/core/styles"
import ImgMediaCard from "./../../../components/Cartao"
import AlertDialog from './../../../components/Modal'
export default function PortfolioSection(props) {
let arrayProjetos = props.projects;
const [selectedId, setSelectedId] = React.useState(0);
const [open, setOpen] = React.useState(false);
const handleClickOpen = (id) => {
setSelectedId(id);
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
let projetos = arrayProjetos.edges[selectedId].node.frontmatter;
return (
<Container>
{arrayProjetos.edges.map(
function criaCard(e, index){
let title = e.node.frontmatter.name;
let imageCard = e.node.frontmatter.images[0];
return (
<>
<ImgMediaCard
alt={title}
imagetitle={title}
texttitle={title}
src={imageCard}
click={() => handleClickOpen(index)}>
</ImgMediaCard>
</>
)
}
)}
<AlertDialog
imageModal={projetos.images[1]}
open={open}
handleClose={handleClose}
title={projetos.name}
text={projetos.description} />
</Container>
)
}
I'm using hooks to open the right modal when I click the "See more" button in the card, its working ok, I have 6 cards now, but I can add more in the future. I just need to limit how many cards I see when I enter the page and have a button to show everything.
API: you can add a pagination and total properties to your api call which returns 2 cards by default and you can handle the count of cards by increasing the pagination value. You may notice to add check to avoid situations like count > total.
UI: you can add const [cardCount, setCardCount] = useState(2)
and map through your cards array until the index not greater than cardCount value:
{arrayProjetos.edges.map((e, index) => { return index <= cardCount && <ImgMediaCard ... /> })}
<Box display={cardCount === 2 ? 'none' : 'block'}>
<Button
onClick={()=> arrayProjetos.edges.length - cardCount === 3 ? setCardCount(...cardCount - 1) : setCardCount(...cardCount - 2)}>See less</Button>
</Box>
<Box display={cardCount === arrayProjetos.edges.length ? 'none' : 'block'} >
<Button
onClick={() => arrayProjetos.edges.length - cardCount === 1 ? setCardCount(...cardCount + 1) : setCardCount(...cardCount + 2)}>See more </Button>
</Box>
How are you getting the cards?
You need to lazy load, if you are getting from a server, you can implement pagination, so the server sends back 2 cards every time (or based on a page data you send to server)
So every time you click the "load more" button, you fire a function who ask server for two more cards, and add the response to your cards js variable
Thanks Nazar, I did something similar I guess:
const [showMore, setShowMore] = React.useState(false);
const clickShow = () => {
setShowMore(oldValue => !oldValue);
showMore ? setButtonText("Ver Mais >") : setButtonText("Ver Menos <");
};
arrayProjetos.edges.slice(0, showMore ? arrayProjetos.edges.lenght : 2).map(
function criaCard(e, index){/*same thing here*/})
<button onClick={() => clickShow()}>{buttonText}</button>
I used slice to limit the array and a hook to change value