user3378165
user3378165

Reputation: 6896

OnClick event on Link component

I have a page with a few NavLinks, I need to set the parent's state with the name of the clicked NavLink, how can I do that if NavLinks doesn't have an OnClick` event?

I would want to do something like that:

<Tile to="./request" department={item.catName} key={item.id} 
      onClick={() => this.setState(catId: item.id)} />

But the onClick doesn't seem to get fired.

export default class extends Component {
  state = {
  };

  componentDidMount() {
    this.props.handleChange(this.state);
  }

  componentDidUpdate(_, prevState) {
     if (this.state !== prevState) {
        this.props.handleChange(this.state);
     }
  }

  render() {
    const { categoriesWithSub } = this.props.categoriesWithSub;
    return (
        {categoriesWithSub &&
          categoriesWithSub.map(item => (
            <Tile
              to="./request"
              department={item.catName}
              key={item.id}
            />
          ))}
      </div>
    );
  }
}

export function Tile({ to, department, onClick }) {
  return (
    <NavLink to={to} css={tile} onClick={onClick}>
      {department}
    </NavLink>
  );
}

Upvotes: 1

Views: 8154

Answers (1)

nipek
nipek

Reputation: 850

The Navlink need the onClick that is been passed from your custom component Tile

change the export function to

export function Tile({ to, department, onClick }) {
  return (
    <NavLink to={to} css={tile} onClick={onClick}>
      {department}
    </NavLink>
  );
}

Upvotes: 4

Related Questions