My App.js have this structure.
return (
<Container fluid="true" className="h-100">
<Header />
<Row className="contentRow">
<CustomerList />
<DetailPage />
</Row>
</Container>
);
There are many elements in CustomerList. With a click I want to send the ID of the element to DetailPage and display the details of the associated element. But I am still quite new in react and don't really know how to pass the data. Or if I even need to change something in the structure of the components.
You need to define a new state variable in your component.
Then please pass it with the setter function into CustomerList.
Define state variable.
const [id, setId] = useState(null);
Then pass setter function into <CustomerList />
<CustomerList setId={setId} />
// on CustomerList click event
const onClick = (event) => {
// your logic and use setId from props.
// This is just an example.
props.setId(event.target.value);
}
Finally, pass id state variable into <DetailPage /> so that your DetailPage component uses in its props.
<DetailPage id={id} />
Usage in Detailpage:
const DetailPage = (props) => {
const id = props.id;
// use id for your purpose.
}
You can use the event.target.id property. add an onclick function:
onClick={(e) => handleClick(e)}
handleClick = (e) => {
//access e.target.id here
}
See if this help you:
import React, { useState } from "react";
const Header = () => <div />;
const CustomerList = ({ onChange }) => (
<ul>
{["item1", "item2", "item3", "item4"].map((item) => (
<li onClick={() => onChange(item)} key={item}>
{item}
</li>
))}
</ul>
);
const DetailPage = ({ selectedItem }) => <div>{selectedItem}</div>;
const Component = () => {
const [selectedItem, setSelectedItem] = useState(null);
const handleChange = (item) => {
setSelectedItem(item);
};
return (
<div> {/* Container */}
<Header />
<div className="contentRow"> {/* Row */}
<CustomerList onChange={handleChange} />
<DetailPage selectedItem={selectedItem} />
</div>
</div>
);
};
When you click some item, we set the state in parent component, and then send to DetailPage, in DetailPage, you can use this selectedItem to show the info.You also can replace ["item1", "item2", "item3", "item4"] with an array of objects.
App.js
import "./styles.css";
import React, { useState } from "react";
import CustomersList from "./CustomersList";
import { DetailPage } from "./DetailPage";
export default function App() {
const [listOfElements, setListOfElements] = useState([
{ name: "abc", id: "0" },
{ name: "def", id: "1" },
{ name: "ghi", id: "2" },
{ name: "jkl", id: "3" },
{ name: "mno", id: "4" }
]);
const [selectedId, setSelectedId] = useState(1);
const [customerDEatiledinfo, setCuatomerDetailedInfo] = useState({
name: "sample"
});
const idSelectedHandler = (id) => {
const idd = +id;
const newState = listOfElements[idd];
setCuatomerDetailedInfo(newState);
};
return (
<div className="App">
<CustomersList customers={listOfElements} selectId={idSelectedHandler} />
<DetailPage customer={customerDEatiledinfo} />
</div>
);
}
CustomersList.js
export const CustomersList = (props) => {
const onClickHandler = (id) => {
props.selectId(id);
};
return (
<div>
{props.customers.map((customer) => {
return (
<div key={customer.id} onClick={()=>onClickHandler(customer.id)}>
{customer.name}
</div>
);
})}
</div>
);
};
export default CustomersList;
DeatilPage.js
export const DetailPage = (props) => {
return <div style={{ color: "blue" }}>
<br/>
DetailPage
<p>{props.customer.name}</p></div>;
};
Related
I'm passing an array of objects to a child as props, and I wanted the child component to re-render when the aray changes, but it doesn't:
parent:
export default function App() {
const [items, setItems] = useState([]);
const buttonCallback = () => {
setItems([...items, { text: "new item" }]);
};
return (
<div className="App">
<h1>Items list should update when I add item</h1>
<button onClick={buttonCallback}>Add Item</button>
<Items />
</div>
);
}
child:
const Items = ({ itemlist = [] }) => {
useEffect(() => {
console.log("Items changed!"); // This gets called, so the props is changing
}, [itemlist]);
return (
<div className="items-column">
{itemlist?.length
? itemlist.map((item, i) => <Item key={i} text={item.text + i} />)
: "No items"}
<br />
{`Itemlist size: ${itemlist.length}`}
</div>
);
};
I found this question with the same issue, but it's for class components, so the solution doesn't apply to my case.
Sandbox demo
<Items propsname={data} />
const buttonCallback = () => {
setItems([...items, { text: "new item" }]);
};
but you should put it as:
const buttonCallback = () => {
setItems([...items, { text: "new item", id: Date.now() }]);
};
Because is not recommended to use index as a key for react children. Instead, you can use the actual date with that function. That is the key for React to know the children has changed.
itemlist.map((item) => <Item key={item.id} text={item.text} />)
Try below:
you are adding array as a dependency, to recognise change in variable, you should do deep copy or any other thing which will tell that useEffect obj is really different.
`
const Items = ({ itemlist = [] }) => {
const [someState,someState]=useState(itemlist);
useEffect(() => {
someState(itemlist)
}, [JSON.stringify(itemlist)]);
return (
<div className="items-column">
{someState?.length
? someState.map((item, i) => <Item key={i} text={item.text
+ i}
/>)
: "No items"}
<br />
{`Itemlist size: ${someState.length}`}
</div>
);
};
I am a beginner in react js programming. I'm trying to do the todo project, which is a classic project. When I delete or add an element from the list, the newly formed list appears on the screen by combining with the previous one, I will show it with a picture below. I did not understand the source of the eror so wanted to post it here to get some advices suggestions about why it is happening.Thank you.(I am getting and storing data in firebase firestore database)
Before Adding an element initial array state
After adding an element to the array.
I am using useState for array and using useEffect to get initial data
MainPage.js that contains form and the list components.
const MainPage = () => {
const [isLoading, setLoding] = useState(true);
const [array, setArray] = useState([]);
const sub = async (email) => {
var result = [];
await onSnapshot(doc(db, "users", email), (doc) => {
var data = doc.data().todos;
data.forEach((element) => {
Object.keys(element).map(() => {
result.push(element["title"]);
});
});
setArray(result);
setLoding(false);
});
};
useEffect(() => {
sub(auth.currentUser.email);
}, []);
const onAddToDo = (todoTitle) => {
setArray((prevAray) => {
return [...prevAray, todoTitle];
});
};
const onRemove = (title) => {
setArray((prevAray) => {
return [array.pop(array.indexOf(title))];
});
};
return (
<div>
{isLoading && <h1>Loading</h1>}
{!isLoading && (
<div>
<section>
<NavBar></NavBar>
<ToDoForm passData={onAddToDo} />
</section>
<section>
<CardList removeCards={onRemove} array={array} />
</section>
</div>
)}
</div>
);
};
export default MainPage;
Firebase.js that stores the firebase update methods
export const deleteItem = (title) => {
updateDoc(doc(db, "users", auth.currentUser.email), {
todos: arrayRemove({ title: title }),
});
};
export const addnewTodo = (title) => {
updateDoc(doc(db, "users", auth.currentUser.email), {
todos: arrayUnion({ title: title }),
});
};
TodoForm.js component
const ToDoForm = (props) => {
const [todoTitle, setTitle] = useState("");
const titleChangeHandler = (event) => {
setTitle(event.target.value);
};
const newTodoAdder = (event) => {
event.preventDefault();
addnewTodo(todoTitle);
props.passData(todoTitle);
};
return (
<div className="form_holder">
<div className="form_container">
<form onSubmit={newTodoAdder}>
<h3>Add Events</h3>
<label>Title</label>
<input
onChange={titleChangeHandler}
type="text"
placeholder="Title"
id="title"
></input>
<div className="holder">
<button type="sumbit">Add</button>
</div>
</form>
</div>
</div>
);
};
export default ToDoForm;
CardList.js component
const CardList = (props) => {
const array = props.array;
if (array.length === 0) {
return (
<div className="grid_container">
<h2>Found no todos</h2>
</div>
);
}
return (
<div className="grid_container">
{array.map((element, index) => {
return (
<Card
removeSelf={() => {
props.removeCards(element);
}}
key={index}
title={element}
/>
);
})}
</div>
);
};
export default CardList;
Card.js component
const Card = (props) => {
const handleRemove = (event) => {
event.preventDefault();
deleteItem(props.title);
props.removeSelf();
};
return (
<div className="card">
<h2 className="card__title">{props.title}</h2>
<button type="button" onClick={handleRemove}>
Delete
</button>
</div>
);
};
export default Card;
EDIT ;
Index.js file
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { BrowserRouter } from "react-router-dom";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<BrowserRouter>
<App />
</BrowserRouter>
);
SOLUTION
I fixed the issue by changing the add and remove functions that were inside of MainPage.js file You can see the new versions bellow. Hope someday it will help somebody.
Use effect was called once all I had to do get the data again after a change...
New Remove and Add functions
const onAddToDo = (todoTitle) => {
console.log(todoTitle + " Added");
sub(auth.currentUser.email);
};
const onRemove = (title) => {
console.log(title + " Deleted");
sub(auth.currentUser.email);
};
So I have a parent Component and a child component. And I use the child component twice in my parent component. I pass them two different state values as props and two different events as props. I have tried to memoize both the callbacks , but both the child are re-rendered even if one child callback is triggred. Why is useCallback not working.
Parent Component:
import { useState, useCallback, useEffect, useMemo } from 'react';
import './App.css'
import List from "./components/list";
import LocalList from "./components/localList";
function App() {
const itemsToBuy = [
'Baby Shoes',
'Grinder',
'Car'
]
const [buyList, updateBuyList] = useState(itemsToBuy);
const [sellList, updateSellList] = useState([
'Bed',
'Sofa'
]);
/** code to check the re-rendering of the componnet */
useEffect(() => {
console.log(`parent is being rendered`)
})
/**trying to update the state from internal method to be passed as props */
const updateBuyClick = useCallback(val => {
updateBuyList(prev => [...prev, val])
}, [buyList])
const updateSellClick = useCallback(val => {
console.log('memo of sell is called')
updateSellList(prev => [...prev, val])
}, [sellList])
return (
<>
<div className='container'>
<div>
<h1>Items To Buy</h1>
<List itemsArray={buyList} onUpdateClick={updateBuyClick} buttonText='Add Items to Buy' idx={'list One'}></List>
</div>
<div>
<h1>Items to Sell</h1>
<List itemsArray={sellList} onUpdateClick={updateSellClick} buttonText='Add Items to Sell' idx={'list Two '}></List>
</div>
{/* <div>
<h1>List that is not re-rendere</h1>
<LocalList buttonText='Add Items to LocalList' idx={'list3 '}></LocalList>
</div> */}
</div>
</>
);
}
export default App;
Child Component:
import { useState , useEffect} from "react";
import './list.css'
function List({ itemsArray = [], buttonText, onUpdateClick, idx }) {
let currentSell = '';
useEffect(() => {
console.log(`${idx} is being rendered`)
})
const updateCurrentSell = (val) => {
currentSell = val;
}
return (
<>
<ul>
{itemsArray.map((value, index) => {
return <li key={index}>{value}</li>
})}
</ul>
<div>
<input type='text' onChange={(e) => { updateCurrentSell(e.target.value) }}></input>
<button onClick={() => { onUpdateClick(currentSell) }}>{buttonText}</button>
</div>
</>
)
}
export default List;
There are two reasons that's not working:
You're telling useCallback to throw away the stored copy of your function when the buyList or sellList changes by including those in your dependencies array. You don't need those dependencies, because you're (correctly) using the callback version of the state setters. So you aren't using buyList or sellList in the callbacks. Just remove them from the arrays.
const updateBuyClick = useCallback(val => {
updateBuyList(prev => [...prev, val])
}, [])
// ^^−−− empty
const updateSellClick = useCallback(val => {
console.log('memo of sell is called')
updateSellList(prev => [...prev, val])
}, [])
// ^^−−− empty
useCallback only does half the necessary work: making sure the functions don't change unnecessarily. But your List component has to do the other half of the work: not re-rendering if its props don't change. With a function component, you do that with React.memo:
const List = React.memo(function List({ itemsArray = [], buttonText, onUpdateClick, idx }) {
// ...
});
React.memo memoizes the component and reuses its last rendering if its props don't change. (You can customize that by providing a callback as its second argument, see the documentation for details.)
Between those two changes, you'll see only the appropriate instances of List re-render when things change.
Live Example:
const { useState, useCallback, useEffect, useMemo } = React;
function App() {
const itemsToBuy = [
"Baby Shoes",
"Grinder",
"Car"
];
const [buyList, updateBuyList] = useState(itemsToBuy);
const [sellList, updateSellList] = useState([
"Bed",
"Sofa"
]);
// *** Note: No need for this to be in `useEffect`
console.log(`parent is being rendered`)
const updateBuyClick = useCallback(val => {
updateBuyList(prev => [...prev, val]);
}, []);
const updateSellClick = useCallback(val => {
updateSellList(prev => [...prev, val])
}, []);
return (
<div className="container">
<div>
<h1>Items To Buy</h1>
<List itemsArray={buyList} onUpdateClick={updateBuyClick} buttonText="Add Items to Buy" idx={"list One"}></List>
</div>
<div>
<h1>Items to Sell</h1>
<List itemsArray={sellList} onUpdateClick={updateSellClick} buttonText="Add Items to Sell" idx={"list Two "}></List>
</div>
</div>
);
}
const List = React.memo(function List({ itemsArray = [], buttonText, onUpdateClick, idx }) {
// *** `currentSell` stuff should be in state, not a local variable
const [currentSell, setCurrentSell] = useState("");
console.log(`${idx} is being rendered`);
return ( // <>...</> is fine, I had to change it because the
// version of Babel Stack Snippets use is out of date
<React.Fragment>
<ul>
{itemsArray.map((value, index) => {
return <li key={index}>{value}</li>
})}
</ul>
<div>
<input type="text" onChange={(e) => { setCurrentSell(e.target.value); }}></input>
<button onClick={() => { onUpdateClick(currentSell); }}>{buttonText}</button>
</div>
</React.Fragment>
);
});
ReactDOM.render(<App />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>
I am very new to react and javascript, but I am trying to build a simple ToDo App. It wasn't complicated until I wanted to read data from a file and to display that data on the screen. The problem is that I don't know how to create a new Todo object to pass it as parameter for addTodo function.. Thaaank you all and hope you can help me!!
I will let the code here (please see the -loadFromFile- function, there is the problematic place:
import React, { useState } from 'react';
import TodoForm from './TodoForm';
import Todo from './Todo';
import data from './data/data.json'
function TodoList() {
const [todos, setTodos] = useState([]);
const loadFromFile = data.map( ( data) => {
const newTodo = addTodo(new Todo(data.id,data.text));
return ( {newTodo} )});
const addTodo = todo => {
if (!todo.text || /^\s*$/.test(todo.text)) {
return;
}
const newTodos = [todo, ...todos];
setTodos(newTodos);
console.log(...todos);
};
const updateTodo = (todoId, newValue) => {
if (!newValue.text || /^\s*$/.test(newValue.text)) {
return;
}
setTodos(prev => prev.map(item => (item.id === todoId ? newValue : item)));
};
const removeTodo = id => {
const removedArr = [...todos].filter(todo => todo.id !== id);
setTodos(removedArr);
};
const completeTodo = id => {
let updatedTodos = todos.map(todo => {
if (todo.id === id) {
todo.isComplete = !todo.isComplete;
}
return todo;
});
setTodos(updatedTodos);
};
return (
<>
<TodoForm onSubmit={addTodo} />
{loadFromFile}
<Todo
todos={todos}
completeTodo={completeTodo}
removeTodo={removeTodo}
updateTodo={updateTodo}
/>
</>
);
}
export default TodoList;
I want to create new instance of Todo object. I tried many times, many different forms, but still doesn't work. I have an id and a text from the data.json file. I want to create that instance of Todo object with these two values. But how?
import React, { useState } from 'react';
import TodoForm from './TodoForm';
import EditIcon from '#material-ui/icons/Edit';
import DeleteIcon from '#material-ui/icons/Delete';
const Todo = ({ todos, completeTodo, removeTodo, updateTodo }) => {
const [edit, setEdit] = useState({
id: null,
value: ''
});
const submitUpdate = value => {
updateTodo(edit.id, value);
setEdit({
id: null,
value: ''
});
};
if (edit.id) {
return <TodoForm edit={edit} onSubmit={submitUpdate} />;
}
return todos.map((todo, index) => (
<div
className={todo.isComplete ? 'todo-row complete' : 'todo-row'}
key={index}
>
<p> <div key={todo.id} onClick={() => completeTodo(todo.id)}>
{todo.text}
</div>
</p>
<div className='icons'>
<DeleteIcon fontSize="small"
onClick={() => removeTodo(todo.id)}
className='delete-icon'
/>
<EditIcon
onClick={() => setEdit({ id: todo.id, value: todo.text })}
className='edit-icon'
/>
</div>
</div>
));
};
export default Todo;
import React, { useState, useEffect, useRef } from 'react';
import { Fab, IconButton } from "#material-ui/core";
import AddIcon from '#material-ui/icons/Add';
function TodoForm(props) {
const [input, setInput] = useState(props.edit ? props.edit.value : '');
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus();
});
const handleChange = e => {
setInput(e.target.value);
};
const handleSubmit = e => {
e.preventDefault();
props.onSubmit({
id: Math.floor(Math.random() * 10000),
text: input
});
setInput('');
};
return (
<form onSubmit={handleSubmit} className='todo-form'>
{props.edit ? (
<>
<textarea cols="10"
placeholder='Update item'
value={input}
onChange={handleChange}
name='text'
ref={inputRef}
className='todo-input edit'
/>
<button onClick={handleSubmit} className='todo-button edit'>
Save
</button>
</>
) : (
<>
<input
placeholder='Add item'
value={input}
onChange={handleChange}
name='text'
className='todo-input'
ref={inputRef}
/>
<Fab color="primary" aria-label="add">
< AddIcon onClick={handleSubmit} fontSize="small" />
</Fab>
</>
)}
</form>
);
}
export default TodoForm;
Issue
Ah, I see what you are getting at now, you are wanting to load some list of todos from an external file. The main issue I see in your code is that you are attempting to call/construct a Todo React component manually and this simply isn't how React works. You render data/state/props into JSX and pass this to React and React handles instantiating the components and computing the rendered DOM.
const loadFromFile = data.map((data) => {
const newTodo = addTodo(new Todo(data.id, data.text));
return ({newTodo});
});
Todo shouldn't be invoked directly, React handles this.
Solution
Since it appears the data is already an array of objects with the id and text properties, it conveniently matches what you store in state. You can simply pass data as the initial todos state value.
const [todos, setTodos] = useState(data);
If the data wasn't readily consumable you could create an initialization function to take the data and transform/map it to the object shape your code needs.
const initializeState = () => data.map(item => ({
id: item.itemId,
text: item.dataPayload,
}));
const [todos, setTodos]= useState(initializeState);
Running Example:
import data from "./data.json";
function TodoList() {
const [todos, setTodos] = useState(data); // <-- initial state
const addTodo = (text) => {
if (!text || /^\s*$/.test(text)) {
return;
}
setTodos((todos) => [todo, ...todos]);
};
const updateTodo = (id, newTodo) => {
if (!newTodo.text || /^\s*$/.test(newTodo.text)) {
return;
}
setTodos((todos) => todos.map((todo) => (todo.id === id ? newTodo : todo)));
};
const removeTodo = (id) => {
setTodos((todos) => todos.filter((todo) => todo.id !== id));
};
const completeTodo = (id) => {
setTodos((todos) =>
todos.map((todo) =>
todo.id === id
? {
...todo,
isComplete: !todo.isComplete
}
: todo
)
);
};
return (
<>
<TodoForm onSubmit={addTodo} />
<Todo
todos={todos}
completeTodo={completeTodo}
removeTodo={removeTodo}
updateTodo={updateTodo}
/>
</>
);
}
i'm trying to work on a todo app with the option of editing.
the goal is to click on the edit button and that'll open an input field, type the new editted text and then have two choices , save the changes or not.
i've managed to write the code for it to open the input field, and to be able to click on the button to not save changes ,but what happens is that it opens the input field for all of the todos ,and whenever i try to update the value of the specific todo i get the error "todos.map is not a function".
Here's the TodoList.js
import Todo from "./Todo";
import AddTodo from "./AddTodo";
import { v4 as uuidv4 } from "uuid";
const TodoList = () => {
//Handlers Add/Remove/RemoveAll/Edit
const addTodoHandler = (input) => {
setTodos([
...todos,
{
name: input,
id: uuidv4(),
},
]);
};
const changeEditMode = (id) => {
setEditMode(!editMode);
console.log(id);
};
const removeTodosHandler = () => {
if (window.confirm("Are you sure you want to delete everything?")) {
setTodos([]);
}
};
const removeTodoHandler = (id) => {
setTodos(todos.filter((todo) => todo.id !== id));
};
const updateValue = (id) => {
inputRef.current.focus();
setEditMode(!editMode);
setTodos({ name: inputRef.current.value });
};
//Todo list states.
const inputRef = useRef("");
const [todos, setTodos] = useState([]);
const [editMode, setEditMode] = useState(false);
return (
<div>
<div>
{todos.map((todo) => {
return (
<div>
{editMode ? (
<div>
{" "}
<input
type="text"
defaultValue={todo.name}
ref={inputRef}
></input>
<button onClick={(e) => updateValue(todo.id)}>ok</button>
<button onClick={(e) => setEditMode(!editMode)}>x</button>
</div>
) : (
<div></div>
)}
<Todo name={todo.name} key={todo.id} />
<button onClick={() => removeTodoHandler(todo.id)}>X</button>
<button onClick={(e) => changeEditMode(todo.id)}>Edit</button>
</div>
);
})}
</div>
<AddTodo
handleAddTodo={addTodoHandler}
removeTodosHandler={removeTodosHandler}
revemoveTodoHandler={removeTodoHandler}
/>
</div>
);
};
export default TodoList;
and here's the Todo.js
const Todo = ({ name }) => {
return (
<div>
<div>{name}</div>
</div>
);
};
export default Todo;
Any help appreciated!
Your updateValue function is setting your todos to an object. So it gives you that error because you can't use map method for objects.
In your updateValue method you are setting your todoList to and object.
const updateValue = (id) => {
inputRef.current.focus();
setEditMode(!editMode);
setTodos({ name: inputRef.current.value });
};
But what you have to do is first find out the item with the id and then update the name property of that object and then again set the new array to setTodos setter.
Like this:
const clonedTodos = todos;
const todoIndex = clonedTodos.findIndex((todo) => todo.id === id);
const updatedTodo = {
...clonedTodos[todoIndex],
name: inputRef.current.value,
};
const updatedTodos = [...clonedTodos];
updatedTodos[todoIndex] = updatedTodo;
setTodos(updatedTodos);