How to push an array with a hook on react js? - reactjs

I'm trying to render an array of value . This is basicaly a to do list and i want to render different value with the button "en cours"
My .map doesn't seems to work and my array just record one value. someone can help me ?
There is also an other problem, when i write on my input my letters just disappeared directly ??
function Task() {
const [task, setTask] = useState("");
const [encours, setEncours] = useState("");
let toDo = [];
const handleInputTask = (e) => {
setTask(e.target.value);
setEncours("en cours");
};
function AddTask() {
toDo.push(task);
console.log(toDo);
}
const switchEnCours = () => {
setEncours("terminé");
};
const deleteTask = () => {
setEncours("supprimée");
};
function RenderMesTasks() {
return (
<div>
<input onChange={handleInputTask}></input>
<button onClick={AddTask}>Valider</button>
<div className="DivColonne">
<div className="Colonne">
<h1>Tâche à faire</h1>
{toDo !== "" && encours === "en cours" ? (
toDo.map((insertTask) => {
<div>
<p>{insertTask}</p>
<button onClick={switchEnCours}>{encours}</button>
</div>;
})
) : (
<div></div>
)}
</div>
<div className="Colonne">
<h1>Tâche en cours</h1>
{encours === "terminé" ? (
<div>
{toDo.map((insert) => {
return (
<div>
<p>{insert}</p>
<button onClick={deleteTask}>{encours}</button>
</div>
);
})}
</div>
) : (
<div></div>
)}
</div>
<div>
<h1>Tâches terminées</h1>
{encours === "supprimée" ? (
<div>
<p>{toDo}</p>
</div>
) : (
<div></div>
)}
</div>
</div>
</div>
);
}
return (
<div>
<h2> Ecrivez une nouvelle tâche</h2>
<div>
<RenderMesTasks />
</div>
</div>
);
}
export default Task;

todos is state:
const [todos,setTodos] = useState([]);
const addToDo = (todo) => setTodos([...todos,todo])

Add this state variable
const [todoList, setTodoList] = useState([]);
and then in your AddTask(), add this
function AddTask() {
setTodoList([...todoList, task]);
}

Related

Delete item from array - reactjs

I make a very simple todo list and should be next to each generated items a delete-btn.
How can I write this function via OnClick()?
i have in App.js quite normal array and now should be deleted with Delete-btn any added items.
ShowListComponent:
export default function ShowList ({items}){
const isEmpty = "Die Eingabe Feld muss nicht leer sein";
return(
<div className='itemList'>
{items.map((item) => (
<ul className='itemContainer'>
<li className='item-name'>
{item.itemName}
</li>
<div className='delete-btn'>
<Button type="primary" danger ghost>
Delete
</Button>
</div>
</ul>
))}
</div>
);
}
List Component:
export default function List ({items, setItems}){
const [inputValue, setInputValue] = useState('');
const AddButtonClick = () => {
if (inputValue === ""){
alert("Eingabefeld ist Leer");
return false
} else {
const newItem ={
itemName: inputValue,
};
const newItems = [...items,newItem];
setItems(newItems);
setInputValue('');
}
}
return(
<>
<Input value={inputValue} onChange={(event) =>
setInputValue(event.target.value)}
name='input'
className='addItemInput'
placeholder="Artikel hinzufügen"
/>
<Button
type="primary"
className='btn'
onClick={() => AddButtonClick()}
>Hinzufügen</Button>
</>
)
}
like the AddButtonClick() create deleteButtonClick:
const deleteButtonClick = (index) => {
const newItems = items && items.filter((element , i) => i !== index);
setItems(newItems);
}
pass it to ShowList component and use it like so:
export default function ShowList ({items, deleteButtonClick}){
const isEmpty = "Die Eingabe Feld muss nicht leer sein";
return(
<div className='itemList'>
{items.map((item, index) => (
<ul className='itemContainer'>
<li className='item-name'>
{item.itemName}
</li>
<div className='delete-btn'>
<Button type="primary" danger ghost onClick={() => deleteButtonClick(index)}>
Delete
</Button>
</div>
</ul>
))}
</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;

React <details> - have only one open at a time

I have a component with several elements. I'm trying to figure out how to update the code with hooks so that only one element will be open at a time - when a element is open, the other's should be closed. This is the code:
const HowItWorks = ({ content, libraries }) => {
const Html2React = libraries.html2react.Component;
return (
<HowItWorksContainer>
{content.fields.map((tab, i) => {
const [open, setOpen] = useState(false);
const onToggle = () => {
setOpen(!open);
};
return (
<details
key={i}
onToggle={onToggle}
className={`tab ${open ? "open" : "closed"}`}
>
<summary className="tab__heading">
<div className="wrapper">
<p>{tab.heading}</p>
{open ? (
<i className="icon kap-arrow-minus" />
) : (
<i className="icon kap-arrow-plus" />
)}
</div>
</summary>
<div className="tab__content">
<Html2React html={tab.content} />
</div>
</details>
);
})}
</HowItWorksContainer>
);
};
Instead of having the open state be a boolean, make it be the ID of the element that is open. Then you can have a function that returns if the element is open by comparing the state with the ID.
const HowItWorks = ({ content, libraries }) => {
const [open, setOpen] = useState(0); //Use the element ID to check which one is open
const onToggle = (id) => {
setOpen(id);
};
const isOpen = (id) => {
return id === open ? "open" : "closed";
}
const Html2React = libraries.html2react.Component;
return (
<HowItWorksContainer>
{content.fields.map((tab, i) => {
return (
<details
key={i}
onToggle={onToggle}
className={`tab ${isOpen(i)}`}
>
<summary className="tab__heading">
<div className="wrapper">
<p>{tab.heading}</p>
{!!isOpen(i) ? (
<i className="icon kap-arrow-minus" />
) : (
<i className="icon kap-arrow-plus" />
)}
</div>
</summary>
<div className="tab__content">
<Html2React html={tab.content} />
</div>
</details>
);
})}
</HowItWorksContainer>
);
};

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

Async/await React: objects are not valid, [object promise]

It's my first project working with React, and I'm fetching an API. I'm trying to pass on the data but it keeps giving me the same error however I do it.
Also, I can log the data in the async function addTrade, but it logs twice for some reason?
fetch:
async function asyncData() {
const response = await fetch('https://api.pokemontcg.io/v1/cards?setCode=base1');
const data = await response.json();
return data;
}
my render function:
const addTrade = async () => {
const pokemonList = await asyncData();
const cards = pokemonList.cards;
console.log(cards);
return <>
<div className='add-trade-container'>
<div className='trade-add-window'>
<div id={1} onClick={e => handleActiveTab(e)} className={tradeBoard.activeTab === '1' ? 'trade-tab trade-tab-active' : 'trade-tab'}>
<span className='trade-tab-title'>Has</span>
{tradeBoard.has.map(has =>
<>
<div className={tradeBoard.activeTab === '1' ? 'window window-active' : 'window'}>{has.content}</div>
</>
)}
</div>
<img className='divider' src='./src/assets/img/trade-icon.svg' width='30' height='30'></img>
<div id={2} onClick={e => handleActiveTab(e)} className={tradeBoard.activeTab === '2' ? 'trade-tab trade-tab-active' : 'trade-tab'}>
<span className='trade-tab-title'>Wants</span>
{tradeBoard.wants.map(wants =>
<>
<div className={tradeBoard.activeTab === '2' ? 'window window-active' : 'window'}>{wants.content}</div>
</>
)}
</div>
</div>
<article className='list'>
<label className='search-label' htmlFor='search'>Search a Pokémon
<input className='search-field' type='text' id='search'></input>
</label>
<div className='list-grid'>
{cards.map((card, index) =>
<div onClick={() => handleClickContent(<PokeItem pokemon={card} index={index}/>)} key={index}>
<PokeItem pokemon={card} index={index}/>
</div>
)}
</div>
</article>
<button onClick={handleSeedClick} className='button-add'>Add a trade</button>
</div>
</>;
};
App:
const App = () => {
return useObserver(() => (
<>
{addTrade()}
<div className='trades'>
{showTrades()}
</div>
</>
));
};
const roottype = document.getElementById('root');
const headtype = document.getElementById('header');
ReactDOM.render(<App />, roottype);
ReactDOM.render(<Header />, headtype);
you need to use react hooks for this
first you need to import useState, useCallback from react library like this import React, { useState, useCallback } from "react";
then use useEffect like this:
const addTrade = async () => {
const [cards,setCards] = useState(null)
useEffect(() => {
async function getData() {
try {
const pokemonList = await asyncData();
const cardsList = pokemonList.cards;
setCards(cardsList);
console.log(cardsList);
} catch (error) {
console.log(error);
}
}
getData();
}, [cards]);
return <>
<div className='add-trade-container'>
<div className='trade-add-window'>
<div id={1} onClick={e => handleActiveTab(e)} className={tradeBoard.activeTab === '1' ? 'trade-tab trade-tab-active' : 'trade-tab'}>
<span className='trade-tab-title'>Has</span>
{tradeBoard.has.map(has =>
<>
<div className={tradeBoard.activeTab === '1' ? 'window window-active' : 'window'}>{has.content}</div>
</>
)}
</div>
<img className='divider' src='./src/assets/img/trade-icon.svg' width='30' height='30'></img>
<div id={2} onClick={e => handleActiveTab(e)} className={tradeBoard.activeTab === '2' ? 'trade-tab trade-tab-active' : 'trade-tab'}>
<span className='trade-tab-title'>Wants</span>
{tradeBoard.wants.map(wants =>
<>
<div className={tradeBoard.activeTab === '2' ? 'window window-active' : 'window'}>{wants.content}</div>
</>
)}
</div>
</div>
<article className='list'>
<label className='search-label' htmlFor='search'>Search a Pokémon
<input className='search-field' type='text' id='search'></input>
</label>
<div className='list-grid'>
{cards.map((card, index) =>
<div onClick={() => handleClickContent(<PokeItem pokemon={card} index={index}/>)} key={index}>
<PokeItem pokemon={card} index={index}/>
</div>
)}
</div>
</article>
<button onClick={handleSeedClick} className='button-add'>Add a trade</button>
</div>
</>;
};

Resources