I'm making it so that every component is one element (button, the whole list, a single element...) I'm having trouble figuring out how to make my list print below the form. Tasks are shown in console.log() but I can't seem to get the right data transferred.
Thanks in advance for any help
This is items.jsx code
import React, { useState} from 'react'
import './todo.css'
import List from './list'
import Button from './button';
function Items () {
const [tasks, setTasks] = useState([]);
const [value, setvalue] = useState("");
/* const onChange = (e) => {
setvalue(e.target.value)
// console.log('type')
} */
const onAddTask = (e) =>{
e.preventDefault();
console.log('submit')
const obj = {
name: value ,
id: Date.now(),
};
if (value !== "") {
setTasks(tasks.concat(obj));
setvalue("")
console.log(obj)
}
};
return(
<div className="form">
<header>Your todo list</header>
<input
placeholder="type your task"
value={value}
onChange={(e) => setvalue(e.target.value)}/>
<input type="date" placeholder='Set your date!'/>
<button onClick={onAddTask}>Submit task</button>
<List data = {List}/>
</div>
)
}
export default Items
This is list.jsx code
import React , { useState } from "react";
import "./Items"
import Button from "./button"
const List = (tasks) => {
return(
<div>
{tasks.map}
</div>
)
console.log(task.map)
}
export default List
step 1
Here's a fully functioning demo to get you started -
function Todo() {
const [items, setItems] = React.useState([])
const [value, setValue] = React.useState("")
const addItem = event =>
setItems([...items, { id: Date.now(), value, done: false }])
return <div>
<List items={items} />
<input value={value} onChange={e => setValue(e.target.value)} />
<button type="button" onClick={addItem}>Add</button>
</div>
}
function List({ items = [] }) {
return <ul>
{items.map(item =>
<ListItem key={item.id} item={item} />
)}
</ul>
}
function ListItem({ item = {} }) {
return <li>{item.value}</li>
}
ReactDOM.render(<Todo />, document.body)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.14.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.14.0/umd/react-dom.production.min.js"></script>
start with good state
Note using an Array to store the items is somewhat inefficient for the kinds of operations you will need to perform. Consider using a Map instead. Run the demo again and click on a list item to toggle its state -
const update = (m, key, func) =>
new Map(m).set(key, func(m.get(key)))
function Todo() {
const [items, setItems] = React.useState(new Map)
const [value, setValue] = React.useState("")
const addItem = event => {
const id = Date.now()
setItems(update(items, id, _ => ({ id, value, done: false })))
}
const toggleItem = id => event =>
setItems(update(items, id, item => ({ ...item, done: !item.done })))
return <div>
<List items={items} onClick={toggleItem} />
<input value={value} onChange={e => setValue(e.target.value)} />
<button type="button" onClick={addItem}>Add</button>
</div>
}
function List({ items = new Map, onClick }) {
return <ul>
{Array.from(items.values(), item =>
<ListItem key={item.id} item={item} onClick={onClick(item.id)} />
)}
</ul>
}
function ListItem({ item = {}, onClick }) {
return <li onClick={onClick}>
{ item.done
? <s>{item.value}</s>
: item.value
}
</li>
}
ReactDOM.render(<Todo />, document.body)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.14.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.14.0/umd/react-dom.production.min.js"></script>
do more with less
Functional programming goes a long way in React. Using a curried update function we can take advantage of React's functional updates -
const update = (key, func) => m => // <-
new Map(m).set(key, func(m.get(key)))
function Todo() {
// ...
const addItem = event => {
const id = Date.now()
setItems(update(id, _ => ({ id, value, done: false }))) // <-
}
const toggleItem = id => event =>
setItems(update(id, item => ({ ...item, done: !item.done }))) // <-
// ...
}
but don't stop there
Avoid creating the todo item data by hand { id: ..., value: ..., done: ... }. Instead let's make an immutable TodoItem class to represent our data. A class also gives us an appropriate container for functions that would operate on our new data type -
class TodoItem {
constructor(id = 0, value = "", done = false) {
this.id = id
this.value = value
this.done = done
}
toggle() {
return new TodoItem(id, value, !this.done) // <- *new* data
}
}
Now our Todo component is unmistakable with its intentions -
function Todo() {
// ...
const [items, setItems] = useState(new Map)
const addItem = event => {
const id = Date.now()
setItems(update(id, _ => new TodoItem(id, value))) // <- new TodoItem
}
const toggleItem = id => event =>
setItems(update(id, item => item.toggle())) // <- item.toggle
// ...
}
Related
In my code, I replace these values
const [items, setItem] = useState<string[]>([]);
const [value, setValue] = useState('')
const [error, setValue]= useState('')
to this
type Props = {
items?: string[],
value?: string,
error?: string
}
and then change the following setItem, setValue, setValue which causes the following error
import React, { useRef, useState } from "react";
import ReactDOM from "react-dom";
import Chip from "#material-ui/core/Chip";
import TextField from "#material-ui/core/TextField";
type Props = {
items?: string[],
value?: string,
error?: string
}
export const TagActions = (props:Props) => {
const { items, value, error } = props;
// const [items, setItem] = useState<string[]>([]);
// const [value, setValue] = useState('')
// const [error, setError]= useState('')
const divRef = useRef<HTMLDivElement>(null)
const handleDelete = (item:any) => {
console.log("handleDelete", item)
const result = items?.filter(i => i !== item)
setItem(result)
};
const handleItemEdit = (item:any) =>{
console.log("handleItemEdit", item)
const result = items?.filter(i => i !== item)
items = result // setItem(result)
value = item // setValue(item)
console.log("value", value)
};
const handleKeyDown = (evt:any) => {
if (["Enter", "Tab", ","].includes(evt.key)) {
evt.preventDefault();
var test = value?.trim();
if (test && isValid(test)) {
items?.push(test)
setValue("")
}
}
};
const isValid = (email:any)=> {
let error = null;
if (isInList(email)) {
error = `${email} has already been added.`;
}
if (!isEmail(email)) {
error = `${email} is not a valid email address.`;
}
if (error) {
setError(error);
return false;
}
return true;
}
const isInList = (email:any)=> {
return items?.includes(email);
}
const isEmail = (email:any)=> {
return /[\w\d\.-]+#[\w\d\.-]+\.[\w\d\.-]+/.test(email);
}
const handleChange = (evt:any) => {
setValue(evt.target.value)
// setError("")
};
const handlePaste = (evt:any) => {
evt.preventDefault();
var paste = evt.clipboardData.getData("text");
var emails = paste.match(/[\w\d\.-]+#[\w\d\.-]+\.[\w\d\.-]+/g);
if (emails) {
var toBeAdded = emails.filter((email:any) => !isInList(email));
setItem(toBeAdded)
}
};
return (
<>
<div>
<TextField id="outlined-basic" variant="outlined"
InputProps={{
startAdornment: items?.map(item => (
<Chip
key={item}
tabIndex={-1}
label={item}
onDelete={() => handleDelete(item)}
onClick={() => handleItemEdit(item)}
/>
)),
}}
ref={divRef}
value={value}
placeholder="Type or paste email addresses and press `Enter`..."
onKeyDown={(e) => handleKeyDown(e)}
onChange={(e) => handleChange(e)}
onPaste={(e) => handlePaste(e)}
/>
</div>
{error && <p className="error">{error}</p>}
</>
);
}
I am a beginner in react typescript, so I don't know how to fix this, Please give me a solution to fix this problem
While changing const to let may fix immediate errors in the console, I doubt this will give you the behaviour that you desire.
The main issue here is that you are mutating the value of props, which in general you should never do. Props are used to pass stateful data down from a parent to a child component. If you wish to update the state of this data from the child component, you should pass an update function using props as well. Below gives an example of what I mean by this by implementing the delete item function (no typescript, but hopefully it gets the idea across):
const ParentComponent = () => {
const [items, setItems] = useState(["item1", "item2", "item3"])
const deleteItem = (itemToDelete) => {
//here we use the functional update form of setState which is good practise when the new state depends on the old state
setItems((items) => items.filter((item) => item!==itemToDelete))
}
return <ChildComponent items={items}, onDeleteItem={deleteItem} />
}
const ChildComponent = ({items, onDeleteItem}) => {
//e.g. to delete item2 call
onDeleteItem("item2")
}
This is one of the more confusing patterns in React, but it is very important to get your head around. Only the component where state is declared should actually be updating that state - as it is the only place where you have access to the setState function.
I want to toggle each of the item that I clicked on but Its keeps toggling all the Items. Using the useContext api
import React, { useState, useEffect } from "react";
const MyContext = React.createContext({
addToFavorites: () => {},
likeHandler: () => {},
fetchRequest: () => {},
});
export const MyContextProvider = (props) => {
const [favorites, setfavorites] = useState([]);
const [toggle, setToggle] = useState(false);
const [items, setItems] = useState([]);
const fetchRequest = async () => {
const api_Key = "oLfD9P45t23L5bwYmF2sib88WW5yZ8Xd7mkmhGSy";
const response = await fetch(
`https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?
sol=50&api_key=${api_Key}`
);
const data = await response.json();
const allItems = data.photos.map((item) => {
return {
id: item.id,
title: item.camera.full_name,
img: item.img_src,
date: item.rover.launch_date,
like: false,
};
});
setItems(allItems);
};
const likeHandler = (item) => {
const found = items.find((x) => x.id === item.id);
setToggle((found.like = !found.like));
console.log(found); //this logs the particular item that is clicked on
};
return (
<MyContext.Provider
value={{
likeHandler,
fetchRequest,
toggleLike: toggle,
data: items,
}}
>
{props.children}
</MyContext.Provider>
);
};
export default MyContext;
I also have a NasaCard component where I call the likeHandler function and the toggle state, onClick of the FavoriteIcon from my context.And I pass in the toggle state to a liked props in my styled component to set the color of the favorite Icon
import {
Container,
Image,
Name,
InnerContainer,
Titlecontainer,
Date,
FavouriteContainer,
FavouriteIcon,
ImageContainer,
SocialContainer,
} from "./index";
import MyContext from "../../Context/store";
import React, { useState, useEffect, useContext } from "react";
const NasaCards = (props) => {
const { likeHandler, toggleLike } = useContext(MyContext);
return (
<Container>
<InnerContainer>
<ImageContainer>
<Image src={props.Image} alt="" />
</ImageContainer>
<Titlecontainer>
<Name>{props.title}</Name>
<Date>{props.date}</Date>
<FavouriteContainer>
<FavouriteIcon
liked={toggleLike}
onClick={() => {
likeHandler({
id: props.id,
title: props.title,
Image: props.Image,
});
}}
/>
</InnerContainer>
</Container>
);
};
export default NasaCards;
I think you're making this a little more complicated than it needs to be. For starters you are using a single boolean toggle state for all the context consumers, and then I think you're mixing your like property on the items state array with the toggle state.
The items array objects have a like property, so you can simply toggle that in the context, and then also use that property when mapping that array.
MyContextProvider - Map the items state to a new array, updating the like property of the matching item.
const likeHandler = (item) => {
setItems(items => items.map(
el => el.id === item.id
? { ...el, like: !el.like }
: el
));
console.log(item); // this logs the particular item that is clicked on
};
NasaCards - Use item.like property for the liked prop on FavouriteIcon and pass the entire props object to the likeHandler callback.
const NasaCards = (props) => {
const { likeHandler } = useContext(MyContext);
return (
<Container>
<InnerContainer>
<ImageContainer>
<Image src={props.Image} alt="" />
</ImageContainer>
<Titlecontainer>
<Name>{props.title}</Name>
<Date>{props.date}</Date>
<FavouriteContainer>
<FavouriteIcon
liked={props.like} // <-- use like property
onClick={() => {
likeHandler(props); // <-- props has id property
}}
/>
</FavouriteContainer>
</Titlecontainer?
</InnerContainer>
</Container>
);
};
I have this code , and I want when I click the button both li and the array show the same value at the same time.
I mean in this code when I click on the button
ul would be updated with input value and the array is empty , then when I enter new value and click the button , again ul would be updated correctly but the array shows me previous value of input.
here is the code :
import React, {useState} from 'react';
const App = () => {
const [items, setItems] = useState([]);
const [value, setValue] = useState('');
const addItem = () => {
setItems([ ... items, {
id : items.length,
value : value
}])
console.log(items)
}
return (
<>
<input type = "text" onChange = { (e) => setValue(e.target.value)} value = {value} />
<br />
<button onClick = {addItem}>Add value</button>
<ul>
{
items.map(item => <li key = {item.id}>{item.value}</li>)
}
</ul>
</>
);
}
export default App;
It is getting updated but since the setState is async you can't see that instantly, instead add a useEffect on items to do an action or check when the items have updated
Try it like this
import React, {useState, useEffect} from 'react';
const App = () => {
const [items, setItems] = useState([]);
const [value, setValue] = useState('');
// this informs you about updation of items.
useEffect(() => {
console.log(items);
}, [items]);
const addItem = () => {
setItems([ ... items, {
id : items.length,
value : value
}])
}
return (
<>
<input type = "text" onChange = { (e) => setValue(e.target.value)} value = {value} />
<br />
<button onClick = {addItem}>Add value</button>
<ul>
{
items.map(item => <li key = {item.id}>{item.value}</li>)
}
</ul>
</>
);
}
export default App;
Running code sandbox here
I'm mapping out a state into input fields and have a handler to create a new input by adding to the state new objects. Is there a way to create a SINGLE button to remove the last object in the state? Appreciate your help !
const [data, setData] = useState({
datapoint1: "",
datapoint2: "",
datapoint3: "",
datapoint4: "" });
// This adds new objects to the state
const handleClick = () => {
setData({
...data,
[`datapoint${Object.keys(data).length + 1}`]: ""
});
};
//This dynamically changes the input keys and value stored in state
const handleChange = (datapoint) => (event) =>
setData({
...data,
[datapoint]: event.target.value
});
<button onClick={handleClick}>Click to add</button>
// I would like another button here to remove last input
{Object.keys(data).map((datapoint) => {
return (
<input
style={{ margin: "20px" }}
key={datapoint}
onChange={handleChange(datapoint)}
/>
);
})}
Bear in mind that objects' cannot preserve the order of the keys.
If you need order preserved , you can use Maps instead
Here's a demo
import React, { useState } from "react";
import ReactDOM from "react-dom";
function App() {
const [data, setData] = useState(
new Map(
Object.entries({
datapoint1: "",
datapoint2: "",
datapoint3: "",
datapoint4: ""
})
)
);
// This adds new objects to the state
const handleClick = () => {
const newData = new Map(data);
newData.set(`datapoint${data.size + 1}`, "");
setData(newData);
};
//This dynamically changes the input keys and value stored in state
const handleChange = (datapoint) => (event) => {
const newData = new Map(data);
console.log({ newData });
newData.set(datapoint, event.target.value);
setData(newData);
};
const handleDelete = () => {
const newData = new Map(data);
newData.delete(`datapoint${data.size}`);
setData(newData);
};
return (
<React.Fragment>
<button onClick={handleClick}>Click to add</button>
<button onClick={handleDelete}>Click to rmeove last</button>
// I would like another button here to remove last input
{[...data.keys()].map((datapoint) => {
return (
<input
style={{ margin: "20px" }}
key={datapoint}
onChange={handleChange(datapoint)}
/>
);
})}
</React.Fragment>
);
}
ReactDOM.render(<App />, document.getElementById("container"));
You are looking for the delete keyword for Js Objects
const removeLastStateItem = () => {
let newData = { ...data };
delete newData[`datapoint${Object.keys(data).length}`];
setData(newData);
};
delete obj['my_key'] - remove the my_key key from the obj
I have a list of items that I would like the user to be able to sort and filter by attribute. I figure using selectors is the most efficient way to do this, though I am not sure exactly how? Ideally, I would like the user to select an attribute from a dropdown above the list, then enter the actual value of the attribute into a text field which would trigger a filtering selector using both of those params. For example in a list of cars, the user wants to filter by "make" so they choose "make" from a list of other attributes like "make", "model", "year" etc. and then next to that they could type in "Nissan" and then they get a list of just cars made by Nissan.
import React, { useEffect } from "react";
import { useSelector, useDispatch } from "react-redux";
import { fetchItems } from "../../actions/items";
const ItemList = ({ match }) => {
const items = useSelector((state) => state.items);
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchItems());
}, [dispatch]);
const renderedList =
Object.values(items).length > 0
? Object.values(items)
.map((item) => {
return (
<ListItem key={item.id}>
<ItemCard item={item} handleClick={handleClick} />
</ListItem>
);
})
: null;
return (
<Grid container direction="row" className={classes.cardGrid}>
<Grid item lg={4} className={classes.list}>
<Typography variant="h4" className={classes.title}>
Items
</Typography>
<List dense>{renderedList}</List>
</Grid>
</Grid>
);
};
export default ItemList;
Keep the filter attribute and value in Redux state, and then apply the filtering in a selector.
// selectors.js
const getFilterAttribute = state => state.filterAttribute;
const getFilterValue = state => state.filterValue;
const getFilteredItems = state => {
const filterAttribute = getFilterAttribute(state);
const filterValue = getFilterValue(state);
const items = getItems(state);
if (!filterAttribute || !filterValue) {
return items;
}
// apply your filter the way you need it
return Object.values(items).filter(...)
}
This helps separate the state-selection logic from the presentation logic. Now your component just has to call the selector:
// ItemList.js
const ItemList = (props) => {
const items = useSelector(getFilteredItems);
const renderedList = items.map(item => ...)
return (
...
)
}
EDIT:
The filter component might look like:
const FilterControl = () => {
const dispatch = useDispatch();
const [attribute, setAttribute] = useState('');
const [value, setValue] = useState('');
const onSubmit = () => {
dispatch({ type: 'SET_FILTER', attribute, value });
}
return (
<div>
<label>Attribute</label>
<input value={attribute} onChange={e => setAttribute(e.target.value)} />
<label>Value</label>
<input value={value} onChange={e => setValue(e.target.value)} />
<button onClick={onSubmit}>Filter</button>
</div>
)
}