Skip to content Skip to sidebar Skip to footer

Catching The Link Click When In The Same Component React

I have a NavBar that has a Logo on it, that contains a Link to the Home page '/'. The application starts from the main page and then its UI will start changing based on user's choi

Solution 1:

There is a simple way to communicate this information. Here what I suggest to do:

1.The App component has the state of the application, storing all information needed to both its child Components. Add inside the state a value clicked, that is true if the image was clicked; false otherwise.

  1. Add an event handler inside App component. Pass it to the navbar, so you can use for the image tag.

  2. Pass the state to home via props; when it changes, re-render starts and home knows.

App

classAppextendsComponent {
  state = {
     clicked: false,
  }

 handler = () => { this.setState({clicked: true})}

 componentDidMount() {
  this.timerID = setInterval(
    () =>this.setState({clicked: false}),
    2000
  );
 }

  componentWillUnmount() {
    clearInterval(this.timerID);
  } 

 render() {
   return (
     <div><Navbarclicked={this.handler} /><Homeclick={this.state.clicked} /></div>
   );
  } 
}

exportdefaultApp;

Navbar

classNavbarextendsComponent {
    render() {
      return(
         <buttononClick={this.props.clicked} >Click Me!</button>
      );
     }
}

exportdefaultNavbar;

Home

classHomeextendsComponent {
    render() {
        console.log('rendering...')
      return(
         <p>The logo was clicked: {this.props.click ? "yes" : "no"} </p>
      );
 }
}

exportdefaultHome;

When the click on Button, the state change from false to true and from true to true. After the first click, react actually re-render the home elements, but it looks the same. To show that something happens I use two lifecycle method to reset the value from true to false. Without timer, if there's a log on home, developers can look that rendering happens at each button (or image clicks).

This links can help you now and when you'll have a bit more experience: https://www.pluralsight.com/guides/react-communicating-between-components

Post a Comment for "Catching The Link Click When In The Same Component React"