OnClick Saving Only One ID at a time on UseState Array - ReactJS - javascript

i am trying to save favorite post ids in an array with button click. The thing is currently it is only saving one ID at a time in array and when you click you on another "click here" button , it removes the previous id and show you the current id. Currently my array is not saving previous saved Ids with the new one. I will appreciate it if someone explain why it is not working and is there something wrong in my code while saving the ids.
Screenshot
Code
import React, { useEffect } from 'react'
import Demopic from "../assets/img/demopic/4.jpg";
import { useState, useRef } from 'react';
import { post } from 'jquery';
export default function Post(props) {
const { id, title, body } = props.data;
const [postid,setPostID] = useState([]);
const [isActive, setActive] = useState(false);
function onHandleOnClick(id) {
setPostID([...postid, id]);
};
useEffect(()=>{
console.log(postid);
},[postid]);
return (
<div className="card">
<div className="row">
<div className="col-md-5 wrapthumbnail">
<a href="post.html">
<div className="thumbnail dd" style={{ backgroundImage: 'url(' + Demopic + ')' }}>
</div>
</a>
</div>
<div className="col-md-7">
<div className="card-block">
<h2 className="card-title"><a href={'/post-detail/'+id} key={id}>{title}</a></h2>
<h4 className="card-text">
{body.length > 100 ? `${body.substring(0, 90)}...` : body }
</h4>
<div className="metafooter">
<div className="wrapfooter text-left">
<span className="meta-footer-thumb">
<a href="author.html">
<img className="author-thumb" src="https://www.gravatar.com/avatar/e56154546cf4be74e393c62d1ae9f9d4?s=250&d=mm&r=x" alt="Sal"/></a>
</span>
<span className="author-meta">
<span className="post-name">Steve</span><br/>
<span className="post-date">22 July 2017</span><span className="dot"></span><span className="post-read">6 min read</span>
</span>
<button onClick={(e)=>onHandleOnClick(id)} value={id}>click here</button>
</div>
</div>
</div>
</div>
</div>
</div>
)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

looks like your Post component is a single post, therefore each one of the Post components that you are creating will have their own postId array.
so if you have 10 posts you will have 10 different arrays, to test this, you can click on the same button multiple times and you will see that they array of that component will grow, for example the Id is 4 and you click multiple times you will see [4 ,4, 4, 4.....] and then if you do it on the Id 2 you will see [2, 2, 2, 2....].
to fix this you should have on your parent component the array and then in then pass the update function to your childs, something like this:
const ParentComponent = () => {
const [postid,setPostID] = useState([]);
const [isActive, setActive] = useState(false);
function onHandleOnClick(id) {
setPostID([...postid, id]);
};
useEffect(()=>{
console.log(postid);
},[postid]);
return (<>
<Post clickFavourite={onHandleOnClick} ...other props/>
<Post clickFavourite={onHandleOnClick} ...other props/>
<Post clickFavourite={onHandleOnClick} ...other props/>
<Post clickFavourite={onHandleOnClick} ...other props/>
<Post clickFavourite={onHandleOnClick} ...other props/>
</>)
}
and then in your child component (Post) you should remove the state and the handler and just use the parent function:
function Post(props) {
const { id, title, body } = props.data;
const { clickFavourite } = props;
return (
<button onClick={(e)=>clickFavourite(id)} value={id}>click here</button>
)
}
notice that I deleted a lot of the content of the Post component just to read it easily.
also take into account that this can be done in different ways, this was the first way that came into my mind but you can use global states, states managers, hooks, etc etc. but as far as I see this is the easiest way and will get the job done

Use
const [postid,setPostID] = useState({});
Instead of
const [postid,setPostID] = useState([]);
It will work.

Related

Link of react is not directing to a new page [duplicate]

This question already has an answer here:
React router 6 never unmount component when URL parameter changes
(1 answer)
Closed 13 days ago.
I am making an ecommerce website. If I click a product, the product full description will be displayed in a new page called detailPage and there will be similar product fetched from the API at the bottom of the detailPage. It is working fine till here. But if I click any of the similar product, I want the similar product to be displayed in the detailPage. How can I make it work?
import React, { useEffect, useState } from 'react'
import { useParams } from 'react-router-dom'
import useFetch from '../../Component/UseFetch/useFetch'
import { Link } from 'react-router-dom'
import './detailPage.css'
const DetailPage = () => {
const [item, setItem] = useState([])
const [mainImg, setMainImg] = useState('')
const [sameProduct, setSameProduct] = useState([])
const { loading, products } = useFetch('https://dummyjson.com/products')
const { id } = useParams()
useEffect(()=>{
const product = products.find(product => product.id === Number(id))
if(product){
setItem(product)
setMainImg(product.thumbnail)
}
},[products])
useEffect(()=>{
const allProduct = products.filter(product => product.category === item.category)
setSameProduct(allProduct)
}, [item, products])
return (
loading ? <div style={{
width: '100vw',
height: '100vh',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontSize: '10vw'
}}>Loading...</div> :
<div>
<div>
<h1 className='product-headline'>Product Detail</h1>
</div>
<div className='product-box'>
<div>
{
products && item && (
<div style={{height: '320px'}}>
<img className='main-image' src={mainImg} />
</div>
)
}
<div className='short-img-box'>
{
products && item && item.images && item.images.map((image, id)=>{
return <img className='short-img' key={id} src={image} onClick={()=> setMainImg(image) }/>
})
}
</div>
</div>
<div>
{
products && item && item.price && !isNaN(item.price) && (
<div>
<h1>{item.title}</h1>
<div>
<span>Rating: {item.rating}</span>
<span>Available Stock: {item.stock}</span>
</div>
<div>
<span>{parseInt(item.price + item.price / 100 * 25)}</span><br></br>
<span>{item.price}</span>
</div>
<p>{item.description}</p>
</div>
)
}
<button>Add to cart</button>
</div>
</div>
<div>
<h1 style={{textAlign: 'center'}}>Review section</h1>
</div>
<div>
<h1 className='product-headline'>Similar Products</h1>
<div className='products'>
{
sameProduct.map((product)=>{
const {id, title, description, category, price, thumbnail, images, rating, stock} = product
return (
<div key={id} className='product'>
<Link to={`/detailpage/${id}`}><img src={thumbnail} /></Link>
<div className='product-details'>
<Link className='title' to={`/detailpage/${id}`}><h3>{title}</h3></Link>
<div className='price-rating'>
<p>${price}</p>
<p>Rating: {rating}/5</p>
</div>
</div>
<button className='add-cart'>ADD TO CART</button>
<span className='product-stock'>Stock: {stock}</span>
</div>
)
})
}
</div>
</div>
</div>
)
}
export default DetailPage
It looks to me that your only problem is that id is not included in your useEffect's dependency array. Can you confirm that that the url is updated to the new product id when you click the similar product?
In that case, all you should do is include the id in the dependency array like this to make the useEffect re-run when the id in the URL is changed:
useEffect(()=>{
const product = products.find(product => product.id === Number(id))
if(product){
setItem(product)
setMainImg(product.thumbnail)
}
},[products, id])
I think a good solution for this should be something like this (not find product in array of product, but fetch single product in single request (for details page):
You will add useEffect hook to handle, when id of product changed in URL.
useEffect(()=> {
// i change name of the function, beacuse it's impossible to use hooks inside callbacks
const {loading, poduct} = someFetchFunction('https://dummyjson.com/products');
// save your data in `useReducer` hook (but it's up to you)
}, [id]);
So right now when you change url on this page, this useEffect hook will trigger and get current product
You also have a way to change the useFetch hook, and move useEffect to this hook, so when something changes it will trigger a request, but from my perspective of view my first variant is better

How to toggle class in react, but one component at once(all with the same classes)

let me explain my situation.
I am building a MERN project to my portfolio and I am trying to make a button toggle between the name of an item and a inputfield. So when the user click the pen (edit), it will add a class with the displain:none; in the div with the text coming from the MongoDB data base to hide it and will remove it from the div with the input. I could manage to do it. BUT since the amount of items can inscrease, clicking in one of them cause the toggle in all of them.
It was ok until I send some useState as props to the component.
This is my code from the App.jsx
import React, {useState, useEffect} from "react";
import Axios from "axios";
import "./App.css";
import ListItem from "./components/ListItem";
function App() {
//here are the use states
const [foodName, setFoodName] = useState("");
const [days, setDays] = useState(0);
const [newFoodName, setNewFoodName] = useState("");
const [foodList, setFoodList] = useState([]);
//here is just the compunication with the DB of a form that I have above those components
useEffect(() => {
Axios.get("http://localhost:3001/read").then((response) => {
setFoodList(response.data);
});
}, []);
const addToList = () => {
Axios.post("http://localhost:3001/insert", {
foodName: foodName,
days: days,
});
};
const updateFood = (id) => {
Axios.put("http://localhost:3001/update", {
id: id,
newFoodName: newFoodName,
});
};
return (
<div className="App">
//Here it starts the app with the form and everything
<h1>CRUD app with MERN</h1>
<div className="container">
<h3 className="container__title">Favorite Food Database</h3>
<label>Food name:</label>
<input
type="text"
onChange={(event) => {
setFoodName(event.target.value);
}}
/>
<label>Days since you ate it:</label>
<input
type="number"
onChange={(event) => {
setDays(event.target.value);
}}
/>
<button onClick={addToList}>Add to list</button>
</div>
//Here the form finishes and now it starts the components I showed in the images.
<div className="listContainer">
<hr />
<h3 className="listContainer__title">Food List</h3>
{foodList.map((val, key) => {
return (
//This is the component and its props
<ListItem
val={val}
key={key}
functionUpdateFood={updateFood(val._id)}
newFoodName={newFoodName}
setNewFoodName={setNewFoodName}
/>
);
})}
</div>
</div>
);
}
export default App;
Now the component code:
import React from "react";
//Material UI Icon imports
import CancelIcon from "#mui/icons-material/Cancel";
import EditIcon from "#mui/icons-material/Edit";
//import CheckIcon from "#mui/icons-material/Check";
import CheckCircleIcon from "#mui/icons-material/CheckCircle";
//App starts here, I destructured the props
function ListItem({val, key, functionUpdateFood, newFoodName, setNewFoodName}) {
//const [foodList, setFoodList] = useState([]);
//Here I have the handleToggle function that will be used ahead.
const handleToggle = () => {
setNewFoodName(!newFoodName);
};
return (
<div
className="foodList__item"
key={key}>
<div className="foodList__item-group">
<h3
//As you can see, I toggle the classes with this conditional statement
//I use the same classes for all items I want to toggle with one click
//Here it will toggle the Food Name
className={
newFoodName
? "foodList__item-newName-delete"
: "foodList__name"
}>
{val.foodName}
</h3>
<div
className={
newFoodName
? "foodList__item-newName-group"
: "foodList__item-newName-delete"
}>
//Here is the input that will replace the FoodName
<input
type="text"
placeholder="The new food name..."
className="foodList__item-newName"
onChange={(event) => {
setNewFoodName(event.target.value);
}}
/>
//Here it will confirm the update and toggle back
//Didn't implement this yet
<div className="foodList__icons-confirm-group">
<CheckCircleIcon
className="foodList__icons-confirm"
onClick={functionUpdateFood}
/>
<small>Update?</small>
</div>
</div>
</div>
//here it will also desappear on the same toggle
<p
className={
newFoodName
? "foodList__item-newName-delete"
: "foodList__day"
}>
{val.daysSinceIAte} day(s) ago
</p>
<div
className={
newFoodName
? "foodList__item-newName-delete"
: "foodList__icons"
}>
//Here it will update, and it's the button that toggles
<EditIcon
className="foodList__icons-edit"
onClick={handleToggle}
/>
<CancelIcon className="foodList__icons-delete" />
</div>
</div>
);
}
export default ListItem;
I saw a solution that used different id's for each component. But this is dynamic, so if I have 1000 items on the data base, it would display all of them, so I can't add all this id's.
I am sorry for the very long explanation. It seems simple, but since I am starting, I spent the day on it + searched and tested several ways.
:|

ReactJS prop is not a function - do I need a class component instead of function and call super()?

I'm following this tutorial on YouTube https://youtu.be/b9eMGE7QtTk
The full code can be found here: https://gist.github.com/adrianhajdin/997a8cdf94234e889fa47be89a4759f1
The tutorial was great, but it didn't split all the functionalities into components which is React used for (or I'm so lead to believe).
So we have the App.js
import React, { useState, useEffect } from "react";
import MovieCard from "./MovieCard";
import SearchIcon from "./search.svg";
import "./App.css";
const API_URL = "http://www.omdbapi.com?apikey=b6003d8a";
const App = () => {
const [searchTerm, setSearchTerm] = useState("");
const [movies, setMovies] = useState([]);
useEffect(() => {
searchMovies("Batman");
}, []);
const searchMovies = async (title) => {
const response = await fetch(`${API_URL}&s=${title}`);
const data = await response.json();
setMovies(data.Search);
};
return (
<div className="app">
<h1>MovieLand</h1>
<div className="search">
<input
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
placeholder="Search for movies"
/>
<img
src={SearchIcon}
alt="search"
onClick={() => searchMovies(searchTerm)}
/>
</div>
{movies?.length > 0 ? (
<div className="container">
{movies.map((movie) => (
<MovieCard movie={movie} />
))}
</div>
) : (
<div className="empty">
<h2>No movies found</h2>
</div>
)}
</div>
);
};
export default App;
MovieCards.jsx is as follows:
import React from 'react';
const MovieCard = ({ movie: { imdbID, Year, Poster, Title, Type } }) => {
return (
<div className="movie" key={imdbID}>
<div>
<p>{Year}</p>
</div>
<div>
<img src={Poster !== "N/A" ? Poster : "https://via.placeholder.com/400"} alt={Title} />
</div>
<div>
<span>{Type}</span>
<h3>{Title}</h3>
</div>
</div>
);
}
export default MovieCard;
The app works, but I want to move className="search" to be its own component like Search /.
The code I end up having in App.js is
//at the top of App.jx
import Search from "./Search"
// in const App
<Search prop={searchMovies}/>
And in the new Seach / component
import { useState } from "react";
import SearchIcon from './search.svg';
const Search = ( prop ) => {
const [searchTerm, setSearchTerm] = useState("");
return (
<div className="search">
<input
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
placeholder="Search"
/>
<img
src={SearchIcon}
alt="search"
onClick={() => prop(searchTerm)}
//props used to be searchMovies
/>
</div>
)
}
export default Search;
When typing something in the search field on the app and clicking on the search icon I get the following error:
prop is not a function
If my research has been correct, I need to use a constructor and super()
But it seems like the constructor needs to be called in a class Search instead of const Search as it breaks the code. Is that the case or is there a way to use the constructor in a function component, or is there something else completely that I should do?
Also, if there is a great tutorial you could recommend for super() I'd be really grateful.
Other thing that I want to do is to make a Results component or call it whatever that would have the {movies?.length > 0 ? ( part of the code, but I feel like that will be a different headache.
Basically what I want is to have:
const App = () => {
return (
<div className="app">
<h1>Movie Site</h1>
<Search />
<Results />
</div>
);
};
Or as shown in the picture
Hope all this makes sense. Also, I want to preface that I do not expect anyone to write the code for me, but if it helps me understand this it's appreciated. YT tutorials are appreciated as well.
Okay, after a push in the right direction from jonrsharpe and renaming the props into random things I figured it out.
As jonrsharpe said, my function is prop.prop, so if I wanted to call searchTerm in
onClick={() => prop(searchTerm)}
it should be
onClick={() => prop.prop(searchTerm)}
Now, that works, but looks silly. So renaming the first "prop" in prop.prop and the prop in const Search to searchOnClick leaves searchOnClick.prop(searchTerm) which still works. Great.
Then in App.js renaming prop in Search prop={searchMovies} to searchOnClick={searchMovies} needs to be followed by renaming searchOnClick.prop in Search.jsx to searchOnClick.searchOnClick.
Lastly, we want to destructure the props as jonrsharpe said.
const Search = ( searchOnClick ) => {
would become
const Search = ( {searchOnClick} ) => {
That allows us to remake searchOnClick.searchOnClick(searchTerm) to searchOnClick(searchTerm) only.
The whole point is that the prop calls the whole componentName variable=value but it doesn't take the value of the variable automatically so it needs to be called like prop.variable until destructured where it can be called as variable only.
Now that I figured this out it feels silly spending two days on this. Thanks to jonrsharpe again, and hope this helps to someone else in the future.

Components Will Not Render After a UseState Change

This is a difficult question because there are so many moving parts, but allow me to attempt to explain the scenario before I start shoving code in everyone's face.
My goal is to allow managers to have a screen where all their drivers are displayed. They will have minimal information displayed and an edit button. If the user clicks the edit button they will stay on the same page. There is a useState, const [driverSelected, setDriverSelected] = useState("") that once an edit button is clicked, will call setDriverSelected to be the driver, not just the id. So once an edit button is clicked, an actual new value for driverSelected would look like this...
{id: 'a049c673-da36-48e6-8fbd-32ab925b6178', role: 'USER', firstname: 'STEVEN', lastname: 'MONROE', email: 'TQRGJGNFQVIO', …}
deleted: false
email: "TQRGJGNFQVIO"
firstname: "STEVEN"
id: "a049c673-da36-48e6-8fbd-32ab925b6178"
lastname: "MONROE"
locked: false
phoneNumber: "null"
profilePick: null
role: "USER"
__typename: "Driver"
[[Prototype]]: Object
Based on this, the same page will change from displaying all the drivers to just the one selected, and input fields to change his/her attributes. This all works properly.
From here, you hit submit and it sends a mutation over to the database. This also works. Then, a query is automatically launched to send the user back the new driver data. This also also works. Where everything breaks is once the mutations/queries are run, I also run setDriverSelected({id: -1}) which should render the drivers list again, but nothing appears at all.
I thought it may be an issue with the data flow, but it isn't. I have console.log statements everywhere along the way from the mutation to the re-render, and at every point the console.log statements return exactly what they're supposed to. No errors in the console, no failed fetches or anything like that from the network. I just literally get nothing. I've even tried replacing all the data with static information, still nothing.
The code is all spread out too across about 7 files since I was trying to compartmentalize as much as possible while using React, so bare with the ugly mess of code files you're about to see.
This is the first page in question, the one that is in charge of either rendering the list OR the driver's fields when chosen.
import React from "react";
import { useState } from "react";
import { useRecoilState } from "recoil";
import { userState } from "../../recoil/atoms";
import SideMenu from "../../components/Home/SideMenu/SideMenu";
import DriverCard from "./DriverCard";
import EditDriver from "./EditDriver";
import "../../styles/EditDrivers/EditDriversLanding.css"
const EditDriversLanding = () => {
// Recoil Data
const rawUser = useRecoilState(userState)
console.log(rawUser)
const user = rawUser[0]
// Local states
const [getSearch, setSearch] = useState("")
const [driverSelected, setDriverSelected] = useState({id: -1})
// Based off of what you type in the search bar, it will filter out invalid employees
const filterDriversList = (list) => {
let filteredList = []
if (getSearch == ""){
return list
}
else{
let filterString = getSearch.toUpperCase()
list.forEach( (driver) => {
if (driver.firstname.includes(filterString) || driver.lastname.includes(filterString)){
filteredList.push(driver)
}
})
return filteredList
}
}
// Takes the list of drivers and renders them all into a list of components
const renderDriverCards = (list) => {
let i = 0
console.log("Okay.... like dude you're RIGHT here, RENDER")
console.log(list)
return list.map( (driver)=> {
i++
if (i == 1){
console.log(driver)
console.log("WHY WONT YOU WORK???")
}
return (<DriverCard driver={driver} key={i} setDriverSelected={setDriverSelected} />)
})
}
const renderListOrEditScreen = () => {
// No Driver selected
if (driverSelected.id == -1){
console.log("dude.... render!!!")
return(
<div className="overlay">
<div className="edit-landing-container">
<SideMenu />
<div className="edit-landing-search-bar">
<input type="text" onChange={(event) => setSearch(event.target.value)} />
</div>
<div className="edit-landing-drivers-list">
{renderDriverCards(filterDriversList(user.drivers))}
</div>
</div>
</div>
)
}
// Driver Selected
else{
return(
<div className="overlay">
<div className="edit-landing-container">
<SideMenu />
<div>
<EditDriver driverData={driverSelected} setDriverSelected={setDriverSelected}/>
</div>
</div>
</div>
)
}
}
if (driverSelected.id == -1){
console.log("should be rendering...")
}
return (
<div>
{renderListOrEditScreen()}
</div>
)
}
export default EditDriversLanding
Its worth mentioning again that this file above works perfectly the first time it is rendered, but after a driver is edited, NOTHING renders-- not a single <div>
Here is the file for the <DriverCard />
import React from "react";
import "../../styles/EditDrivers/EditDriversLanding.css"
const DriverCard = ({driver, setDriverSelected}) => {
console.log(driver)
console.log("dude just work bro")
return(
<div className="edit-drivers-driver-card">
<div>
Image
</div>
<div>
<div>{driver.firstname} {driver.lastname}</div>
<div>{driver.email}</div>
<div>{driver.phoneNumber}</div>
<div className="edit-driver-driver-card-edit-button" onClick={() =>setDriverSelected(driver)}>Edit</div>
</div>
</div>
)
}
export default DriverCard
And finally, here is the EditDriver page which is where the mutation and re-query take place. Notice here you'll see a <div> that on press will also setDriverSelected({id: -1}) and THAT one decides to work-- just the submitting changes kills everything.
import React from "react";
import { useState } from "react";
import DriverField from "../../components/EditDrivers/DriverField";
import SubmitEdits from "./submitEdits";
import "../../styles/EditDrivers/EditDriversLanding.css"
const EditDriver = ({driverData, setDriverSelected}) => {
const [driver, setDriver] = useState(driverData)
const handleInput = (event) => {
const input = { ...driver };
input[event.target.id] = event.target.value;
setDriver(input);
};
return(
<div className="edit-driver-editting-page">
<div onClick={() => setDriverSelected({id: -1})} className="edit-driver-editting-page-exit-button">
Return to Driver Selection
</div>
<div>
<h2>Edit {driverData.firstname} {driverData.lastname}</h2>
</div>
<div>
<div>
<DriverField currentValue={driver.firstname} name="firstname" handleInput={handleInput} />
</div>
<div>
<DriverField currentValue={driver.lastname} name="lastname" handleInput={handleInput} />
</div>
<div>
<DriverField currentValue={driver.email} name="email" handleInput={handleInput} />
</div>
<div>
<DriverField currentValue={driver.phoneNumber} name="phoneNumber" handleInput={handleInput} />
</div>
<SubmitEdits driver={driver} setDriverSelected={setDriverSelected}/>
</div>
</div>
)
}
export default EditDriver
It's hard to say why nothing at all is rendering - but it looks like your landing page component is more complex than it needs to be. It's not often that you need to have functions which render content (e.g. renderListOrEditScreen and renderDriverCards) - often that's a sign that you should break those functions out into their own components.
So, I'd suggest you start by splitting that up into smaller components that do less work. It looks like one of the functions of that page is to act as the "search" page - you could split that up using something like this:
const useFilteredDriversList = (drivers, search) => {
return useMemo(() => {
if (!search) return drivers;
const searchUpper = search.toUpperCase();
return drivers.filter(driver =>
driver.firstName.includes(searchUpper) ||
driver.lastName.includes(searchUpper)
);
}, [drivers, search]);
}
const DriverSearch = ({ onDriverSelected }) => {
const [user] = useRecoilState(userState);
const [search, setSearch] = useState("");
const filteredDrivers = useFilteredDriversList(user.drivers, search);
const handleSearchChange = (event) => setSearch(event.target.value);
return (
<>
<div className="edit-landing-search-bar">
<input type="text" onChange={handleSearchChange} />
</div>
<div className="edit-landing-drivers-list">
{filteredDrivers.map(driver => (
<DriverCard
key={driver.id}
driver={driver}
setDriverSelected={onDriverSelected}
/>
))}
</div>
</>
);
}
Note here I've also split out the filtering code from the component - having it inside the component means you're redefining the filter function every time the component renders, which is unnecessary.
OK; now that the search page has been split out, you can just have a landing page component which either shows the search component or the edit component, depending on if a driver has been selected or not. One other thing that I'd do is create an explicit handler for the case of "cancelling" the edit, and have that live in the landing page. The edit page shouldn't have knowledge of how to "cancel" editing (i.e. setting the driver to { id: -1 }) - that's not its responsibility. It should just tell the parent component that it's finished, and let the parent component worry about how to handle that.
Finally, I'd use either null or undefined to represent "no driver selected" rather than a magic object. So, something like this might work:
const DriversPage = () => {
const [driver, setDriver] = useState(undefined);
const handleUnselectDriver = () => setDriver(undefined);
return (
<div className="overlay">
<div className="edit-landing-container">
<SideMenu />
{driver && (
<EditDriver
driverData={driver}
onEditComplete={handleUnselectDriver}
/>
)}
{!driver && (
<DriverSearch onDriverSelected={setDriver} />
)}
</div>
</div>
);
}

Search bar stopping props from changing

On my site, the <ArticleList> is supposed to update when one navigates between columns. This works when you go from the home page to a column, or from an article to a column. But if you go from column to column, it doesn't work. The page doesn't update at all, but the url changes. The links to each column stay the same, as they are part of the <Layout> component, which every page has.
Edit
I figured out now that I can just use <a> and omit <Link> entirely, but this would slow down the page navigation.
Edit 2
This is part of my <Layout> component where I render the links to the columns:
<nav className={layout.columnContainer}>
{columns.map(({ id, name }) =>
this.props.currentColumn ? (
<a key={id} href={`/columns/${name}`}>
{name}
</a>
) : (
<Link key={id} href="/columns/[name]" as={`/columns/${name}`}>
<a>{name}</a>
</Link>
),
)}
</nav>
Edit 3
My minimal reproducible example is on GitHub, and I get the same unexpected results.
Edit 4
I found that the reason it wasn't working was I implemented a search bar that put the children prop in a state and modified this.
Constructor:
constructor(props) {
super(props);
this.searchArticlesKeyType = this.searchArticlesKeyType.bind(this);
this.state = {displayedMain: props.children};
}
Inside the render method are the column links (nav) and the problematic search input element.
<nav className={layout.columnContainer}>
{
columns.map(({id, name}) => (
<Link key={id} href="/columns/[name]" as={`/columns/${name}`}><a>{name}</a></Link>
))
}
</nav>
<div className={layout.search}>
<input type="search" name="q" onKeyUp={this.searchArticlesKeyType} />
</div>
async searchArticlesKeyType(e) {
// Some code
this.setState({
displayedMain: <ArticleList articles={JSON.stringify(filteredArticles)}/>
// More code
});
}
I think your main issue here is the way you're implementing the search feature, you don't want to store components in state instead you need to pass the search text to the articlelist component and do the filtering there.
There are several ways to implement communication between 2 unrelated components, it could be via context, redux, or even make a portal in the layout to render the seach input from the column component, but in this case I think the best option is to store the search text in the url:
First make the input event update the url using next/router, your layout will look like this:
import { useRouter } from 'next/router'
...
function Layout(props) {
const {columns} = props;
const { push, asPath, query } = useRouter()
const searchArticlesKeyType = (e) => {
const q = e.target.value;
const [url] = asPath.split('?');
push(`${url}?q=${q}`, undefined, { shallow: true });
}
return (
<div>
...
<div>
<input type="search" name="q" defaultValue={query.q} onKeyUp={searchArticlesKeyType} />
</div>
...
</div>
)
}
And then you do the filtering in articlelist component
import Link from "next/link";
import { useRouter } from 'next/router'
export default function ArticleList(props) {
const { query } = useRouter();
const q = query.q || "";
const filteredArticles = props.articles.filter(
(item) => item.title.includes(q) || item.body.includes(q)
);
return (
<ul className="grid">
{filteredArticles.map((item) => (
<div key={item.id}>
<Link
key={item.id}
href="/articles/[title]"
as={`/articles/${item.title}`}
>
<a>
<p>
<strong>{item.title}</strong>
</p>
<p>{item.body.substring(0, 100)}</p>
</a>
</Link>
</div>
))}
</ul>
);
}

Categories