Search code examples
reactjsreact-router-domreact-propsuse-state

reactjs Link onClick set props is undefined in child


I'm trying to set props onClick on a Link. but in the History component it is undefined.

export function Item({ id, prePassword, updateList, setPropsPassword }) {
...
<Link onClick={()=>setPropsPassword(password)} to={"/history/"+id} className="btn-open-history float-left btn btn-primary">Geschiedenis</Link>
...
}

parent:

function Store(props) {
  let { id } = props.match.params;
  const [password, setPassword] = useState()
  
  return (
    <>
      <List items={props.items} setPassword={setPassword} selectedId={id}  />
      <AnimatePresence>
        {props.match.path=="/history/:id" && id && <History prePassword={password} id={id} key="item" />}

        {props.match.path=="/list/:id" && id && <Item setPropsPassword={setPassword} updateList={props.updateList} prePassword={password} id={id} key="history" />}

        
      </AnimatePresence>
    </>
  );
}

History Component:

class History extends React.Component {

    constructor(props) {
        super(props);
    }

    componentDidMount() {
        console.log(this.props)
    }
    componentDidUpdate(){ 
        console.log(this.props)
    }
    render() {
        return (...)
    }

So I also have a Link with a onClick in Item and this one is working with the password props. But in the History Component the password props is undefined.

I don't understand why it is undefined in the History component


Solution

  • I have fixed the issue by changing the location of:

    const [password, setPassword] = useState()
    

    to the parent of "Store" and giving the "password" and "setPassword" down to Store.

    But I still don't know why it does not working in Store.