2

I am trying to change the state through a Link component when I click on an image. I'm not sure if it's how the Link component is written or if the clickHandler is incorrectly used, but it console logs the state as true even after I click it.

import React, {useState, useEffect} from 'react'
import {Link, Switch, Route} from 'react-router-dom'
import RecipePage from './RecipePage'
export default function Recipes({dataArray}){

const [strMeal, setStrMeal] = useState(true)

function clickHandler(){
    setStrMeal(false)
}




return(
    <div>
        <Link to={{pathname:'/recipepage', state: {strMeal: strMeal} }}>
            <div onClick={() => clickHandler()}>This is an image</div>
        </Link>
    </div>
    
)

}

How do I change the state to false?

Tommy Wu
  • 21
  • 2
  • react not store the state value until you are using [`useContext`](https://reactjs.org/docs/hooks-reference.html#usecontext) or `redux`. Each time of the navigation that state value reset to default like your `useState(true)` – prasanth May 17 '21 at 14:47

1 Answers1

0

It's recommended to use onClick handler on <Link /> component itself:

<Link to={{pathname:'/recipepage', state: {strMeal: strMeal} }} onClick={(e) => clickHandler(e)}>

Now, you'll also need to prevent the default behavior of the link:

function clickHandler(e){
    e.preventDefault()
    setStrMeal(false)
}

But I am not sure why you want to do this? Since, Link is used to go to the path you provide. So, I guess you want to do something on /recipepage:

So, you'll get the pathname, or even with the state you've provided and do something with that there in the component.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
  • I am trying to open up a page that displays the recipe info depending on which image I click. I have the fetch API ready to go. I would like to send the name of the recipe to the Link component so I could try to get the page to display the info. – Tommy Wu May 17 '21 at 16:13
  • And thank you, but I'm still having the initial issue! – Tommy Wu May 17 '21 at 16:14
  • Do necessary in that component with the props. – Bhojendra Rauniyar May 17 '21 at 17:47