I'm trying to re render my HTML after I have clicked on a badge:
onClick={() => filterCategories(c.category)}
The code:
const BlogPage = props => {
console.log(props);
//After I click on the button comes back with the correct posts.
let posts =
props.data.allContentfulPost !== undefined
? props.data.allContentfulPost.edges
: props.data;
const categoriesStyle = {
marginBottom: '8px',
};
const filterCategories = category => {
posts = posts.filter(p => p.node.category === category);
BlogPage({ data: posts });
};
return(
<span tabIndex="0" key={c.id}
onClick={() => filterCategories(c.category)}
role="button"
onKeyDown={filterCategories}>
<Badge value={c.category} category={c.category} color="#fff">
{c.category}
</Badge>
</span>
)
}
So if I'm not mistaking I have to make use of setState, but when I try to use it I can't do it because is not a class and I will need a class to add the constructor as well right? The problem with this code is that it was writing by someone else using Gatsby and I'm new to React and Gatsby
I'd recommend you maintain the category in state and then filter posts based on that stateful category.
const BlogPage = props => {
const [category, setCategory] = useState(null);
const posts =
props.data.allContentfulPost !== undefined
? props.data.allContentfulPost.edges
: props.data;
const categoriesStyle = {
marginBottom: '8px',
};
const filterCategories = category => {
setCategory(category)
};
// These are your filtered posts
const filteredPosts = category ?
posts.filter(p => p.node.category === category) :
posts;
return(
<span tabIndex="0" key={c.id}
onClick={() => filterCategories(c.category)}
role="button"
onKeyDown={filterCategories}>
<Badge value={c.category} category={c.category} color="#fff">
{c.category}
</Badge>
</span>
)
}
Related
**> This is my Gallery Component **
import React, {useState} from 'react';
import useFirestore from '../hooks/useFirestore';
import { motion } from 'framer-motion';
const Gallery = ({ setSelectedImg }) => {
const { docs } = useFirestore('images');
here im setting the state as a Tags array
const [tags, setTags] = useState([""]);
const addTag = (e) => {
if (e.key === "Enter") {
if (e.target.value.length > 0) {
setTags([...tags, e.target.value]);
e.target.value = "";
}
}
};
functions for adding and removing Tags
const removeTag = (removedTag) => {
const newTags = tags.filter((tag) => tag !== removedTag);
setTags(newTags);
};
return (
<>
<div className="img-grid">
{docs && docs.map(doc => (
< motion.div className="img-wrap" key={doc.id}
layout
whileHover={{ opacity: 1 }}s
onClick={() => setSelectedImg(doc.url)}
>
here Im adding the Tag input to each Image...the problem is that when adding a Tag is added to all the pictures. I want to add the tags for the image that I´m selecting.
<div className="tag-container">
{tags.map((tag, ) => {
return (
<div key={doc.id} className="tag">
{tag} <span onClick={() => removeTag(tag)}>x</span>
</div>
);
})}
<input onKeyDown={addTag} />
</div>
<motion.img src={doc.url} alt="uploaded pic"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: 1 }}
>
</motion.img>
</motion.div>
))}
</div>
</>
)
}
export default Gallery;
The tags array that you are using to store values entered by the user are not unique with respect to each image item. Meaning, every image item in your program is using the same instance of the tags array, what you need to do is
Either create an object that stores an array of tags for each image:
const [tagsObj, setTagsObj] = {}, then while adding a new tag for say image_1, you can simply do setTagsObj(prevObj => {...prevObj, image_1: [...prevObj?.image_1, newTagValue]},
Or create an Image Component which would then handle tags for a single image:
Gallery Component:
{
imageList.map(imageEl =>
<ImageItem key={imageEl} image={imageEl} />
)
}
ImageItem Component:
import {useState} from 'react';
export default function ImageItem({image}) {
const [tags, setTags] = useState([]);
const addTag = (e) => {
if (e.key === "Enter") {
const newVal = e.target.value;
if (newVal.length > 0) {
setTags(prevTags => [...prevTags, newVal]);
e.target.value = '';
}
}
};
const removeTag = (removedTag) => {
setTags(prevTags => prevTags.filter((tag) => tag !== removedTag));
}
return (
<div style={{margin: '12px', padding: '12px', width: '100px', height:'100px', display:'flex', flexDirection: 'column', alignItems:'center'}}>
<span>{image}</span>
{tags.map((tag, index) => {
return (
<div key={tag+index}>
{tag} <span onClick={() => removeTag(tag)}>x</span>
</div>
);
})}
<input onKeyDown={addTag} />
</div>
);
}
Refer this sandbox for ease, if available Gallery unique image tags sandbox
I suggest using the second method, as it is easy to understand and debug later on.
I hope this helps, please accept the answer if it does!
I am learning react and I have some doubts about changing the color onClick
How can I toggle the className of a <p> element that is being clicked? At the moment clicking on one changes the color on everything.
I have read about passing a state on a parent element but at this point is getting a bit confusing and if someone could help me clarifying this would be nice.
Here's the code of my child element:
import "./Answer.scss";
function Answer(props) {
const getAnswers = [];
const correct_answer = props.correct_answer;
getAnswers.push(correct_answer);
for (let i = 0; i < props.incorrect_answers.length; i++) {
getAnswers.push(props.incorrect_answers[i]);
}
const [answers, setAnswer] = useState(getAnswers);
const [active, setActive] = useState(true);
const displayAnswers = answers.map((answer, index) => (
<p
className={active ? "answer" : "answer-active"}
key={index}
onClick={() => setActive((prevState) => !prevState)}
>
{answer.replace(/"|'/g, '"')}
</p>
));
return <div className="answer-box">{displayAnswers}</div>;
}
export default Answer;
And this is the parent:
import Answer from "../Answer/Answer";
function Questions(props) {
const questions = props.questions.map((question, index) => {
return (
<div className="question" key={index}>
<h2>{question.question.replace(/"|'/g, '"')}</h2>
<Answer
incorrect_answers={question.incorrect_answers}
correct_answer={question.correct_answer}
/>
<hr></hr>
</div>
);
});
return <div className="questions-container">{questions}</div>;
}
export default Questions;
Thanks everyone
Check this code.
const [answers, setAnswer] = useState(getAnswers);
const [active, setActive] = useState(true);
const displayAnswers = answers.map((answer, index) => (
<p
className={active ? "answer" : "answer-active"}
key={index}
onClick={() => setActive((prevState) => !prevState)}
>
{answer.replace(/"|'/g, '"')}
</p>
));
You are iterating your answers and updating the same state variable for each answer. It's like you are over-writing the updated values. Instead, you can make a separate state variable for each and every option. Based on the onClick, you can update that specific answer state and use it in the code. Check the below code.
const AnswerText = ({ valid, index, answer }) => {
const [active, setActive] = useState(valid);
return (
<p
className={active ? "answer" : "answer-active"}
key={index}
onClick={() => setActive((prevState) => !prevState)}
>
{answer}
</p>
);
};
You can use the above component in the map and display your answers.
Attached is a sandbox for reference.
import React from 'react'
import { useState, useEffect } from 'react'
import axios from 'axios'
const Home = () => {
const getSongs = () => {
axios.get('http://localhost:8000/api/songs/')
.then(res => setSongs(res.data))
}
let [songs, setSongs] = useState([])
let [paused, setPause] = useState(true)
useEffect(() => {
getSongs()
}, [])
const toggleSong = (id) => {
const x = document.getElementById(id)
if (x.paused){
x.play()
setPause(false)
} else {
x.pause()
setPause(true)
}
}
// Got rid of the functions that are not needed
return (
<>
{
songs.map(song =>
(
<div className='music-controller' key={song.id}>
<div id={'songDiv'} style={{cursor: 'pointer'}} onClick={(e) => changeSongTime(e, song.id)}>
<div id={`songTime-${song.id}`}></div>
</div>
<div className="music-controller-body">
<div className="music-controller-header">
<h2>{song.title}</h2>
<p><small>{song.genre}</small></p>
</div>
<div className="controls">
// here <----------------------
<i unique={song.id} className={`fas fa-${paused ? 'play' : 'pause'}`} onClick={() => toggleSong(song.id)}></i>
<audio id={song.id} onTimeUpdate={() => songTime(song.id)}>
<source src={`http://localhost:8000/api/songs/audio/${song.id}`} />
</audio>
</div>
</div>
</div>
))}
</>
)
}
export default Home
Whenever I click on a specific i element all of the i elements that were not clicked on get changed too.. to put it simply when I click on the 1st i element only its className should change, but all of the i elements classNames are affected, what is causing this?
I think you should use event.target
const handlePlay = (song) => {
song.play();
};
const handlePause = (song) => {
song.pause();
};
...
<div className="controls">
<i
onMouseOver={(e) => handlePlay(e.target)}
onMouseLeave={(e) => handlePause(e.target)}
className={`fas fa-${paused ? 'play' : 'pause'}`}
onClick={() => toggleSong(song.id)}>
</i>
<audio id={song.id} onTimeUpdate={() => songTime(song.id)}>
<source src={`http://localhost:8000/api/songs/audio/${song.id}`} />
</audio>
</div>
I don't think Toggle would work in this case, an action should happen so it knows when it should stop.
Can you put console in toggleSong function at top and check if you are getting correct id. If you are not getting single Id then work is needed with onClick. So, after that also try passing id like this
onClick={(song?.id) => toggleSong(song?.id)}
then see console again and look for correct id if it is displayed or not. I think your className is not updating due to this issue.
One thing more you can try at end is replacing with this
const x = id; //without document.getElementById
const toggleSong = (e, id) => {
const x = document.getElementById(id)
const button = e.currentTarget
if (x.paused){
x.play()
button.className = 'fas fa-pause'
} else {
x.pause()
button.className = 'fas fa-play'
}
}
<i unique={song.id} className='fas fa-play' onClick={(e) => toggleSong(e, song.id)}></i>
I fixed this by just getting the current target with event.currentTarget and change its className accordingly!
i want to optimize my react App by testing with a large list of li
Its a simple todo List.
By exemple, when click on a li, task will be line-through, and check icon will be green. This simple action is very slow with a large list because, the whole list is re render.
How to do this with React Hooks?
function App() {
const [list, setList] = useState([]);
const [input, setInput] = useState("");
const inputRef = useRef(null);
useEffect(() => inputRef.current.focus(), []);
//Pseudo Big List
useEffect(() => {
const test = [];
let done = false;
for (let i = 0; i < 5000; i++) {
test.push({ task: i, done });
done = !done;
}
setList(test);
}, []);
const handlerSubmit = (e) => {
e.preventDefault();
const newTask = { task: input, done: false };
const copy = [...list, newTask];
setList(copy);
setInput("");
};
const checkHandler = (e, index) => {
e.stopPropagation();
const copy = [...list];
copy[index].done = !copy[index].done;
setList(copy);
};
const suppression = (e, index) => {
e.stopPropagation();
const copy = [...list];
copy.splice(index, 1);
setList(copy);
};
const DisplayList = () => {
return (
<ul>
{list.map((task, index) => (
<Li
key={index}
task={task}
index={index}
suppression={suppression}
checkHandler={checkHandler}
/>
))}
</ul>
);
};
//JSX
return (
<div className='App'>
<h1>TODO JS-REACT</h1>
<form id='form' onSubmit={handlerSubmit}>
<input
type='text'
placeholder='Add task'
required
onChange={(e) => setInput(e.target.value)}
value={input}
ref={inputRef}
/>
<button type='submit'>
<i className='fas fa-plus'></i>
</button>
</form>
{list.length === 0 && <div id='noTask'>No tasks...</div>}
<DisplayList />
</div>
);
}
export default App;
Li component
import React from "react";
export default function Li(props) {
return (
<li
onClick={(e) => props.checkHandler(e, props.index)}
className={props.task.done ? "line-through" : undefined}
>
{props.task.task}
<span className='actions'>
<i className={`fas fa-check-circle ${props.task.done && "green"}`}></i>
<i
className='fas fa-times'
onClick={(e) => props.suppression(e, props.index)}
></i>
</span>
</li>
);
}
CodeSandbox here: https://codesandbox.io/s/sad-babbage-kp3md?file=/src/App.js
I had the same question, as #Dvir Hazout answered, I followed this article and made your code the changes you need:
function App() {
const [list, setList] = useState([]);
const { register, handleSubmit, reset } = useForm();
//Pseudo Big List
useEffect(() => {
const arr = [];
let done = false;
for (let i = 0; i < 20; i++) {
arr.push({ id: uuidv4(), task: randomWords(), done });
done = !done;
}
setList(arr);
}, []);
const submit = ({ inputTask }) => {
const newTask = { task: inputTask, done: false, id: uuidv4() };
setList([newTask, ...list]);
reset(); //clear input
};
const checkHandler = useCallback((id) => {
setList((list) =>
list.map((li) => (li.id !== id ? li : { ...li, done: !li.done }))
);
}, []);
const suppression = useCallback((id) => {
setList((list) => list.filter((li) => li.id !== id));
}, []);
//JSX
return (
<div className="App">
<h1>TODO JS-REACT</h1>
<form onSubmit={handleSubmit(submit)}>
<input type="text" {...register("inputTask", { required: true })} />
<button type="submit">
<i className="fas fa-plus"></i>
</button>
</form>
{list.length === 0 && <div id="noTask">No tasks...</div>}
<ul>
{list.map((task, index) => (
<Li
key={task.id}
task={task}
suppression={suppression}
checkHandler={checkHandler}
/>
))}
</ul>
</div>
);
}
Li component
import React, { memo } from "react";
const Li = memo(({ task, suppression, checkHandler }) => {
// console.log each time a Li component re-rendered
console.log(`li ${task.id} rendered.`);
return (
<li
onClick={(e) => checkHandler(task.id)}
className={task.done ? "line-through" : undefined}
>
{task.task}
<span className="actions">
<i className={`fas fa-check-circle ${task.done && "green"}`}></i>
<i className="fas fa-times" onClick={(e) => suppression(task.id)}></i>
</span>
</li>
);
});
export default Li;
You can check it live here
I know it's probably late for your question, but may help others ;)
You can use React.memo and wrap the Li component. This will cache the instances of the Li component based on shallow comparison. Read more in the docs
Otherwise, if you don't need the state in the container, you can keep it locally in the Li component and then it won't cause a whole list rerender.
App won't re render different data on state change.
State does change in the dev tools but doesn't show on page.
Using button to filter.
export const StoriesPage = () => {
const [storyIds, setStoryIds] = useState([]);
const [storyUrl, setStoryUrl] = useState('top');
useEffect(() => {
let url = baseUrl;
storyUrl === 'top'
? (url += 'topstories.json')
: (url += 'newstories.json');
getStoryIds(url).then(data => setStoryIds(data));
}, [storyUrl]);
return (
<div>
<div>
<button onClick={() => setStoryUrl('new')}>New</button>
<button onClick={() => setStoryUrl('top')}>Top</button>
</div>
{storyIds.map((storyId, index) => (
<Story key={index} storyId={storyId} />
))}
</div>
);
};
Added a function that clears storyIds before setStoryUrl
const handleFilter = tag => {
setStoryIds([]);
setStoryUrl(tag);
};