Aklank Jain
Aklank Jain

Reputation: 1062

How to call a component on a click event in react?

I have a simple react application. I want to call a component on a click event. Now what happens is when I click that function, it gets called but that component doesn't change. I tried the checking the path and all everything seems fine as when I put the same component in render it gets executed. Here's my code:

Please let me know what am I doing wrong.

Please ignore some of the wrong if else condition, I have put them trying to bug to no avail.

header.jsx

   class Head extends React.Component {
  handleClick = (e) => {
    console.log(e.key);
    <Cont key1 = e.key />
  }


  render(){
      return( 
      <Header>
        <div className="logo" />
        <Menu
        onClick={ this.handleClick }>
        <Menu.Item key="1">Hungry Rides</Menu.Item>
        <Menu.Item key="2">Hiker's Diary</Menu.Item>
        <Menu.Item key="3">Hiking @ Hometown </Menu.Item>
      </Menu>
    </Header>
    )
  }
}

content.jsx

    class Cont extends React.Component {

  constructor(props) {
    super(props);
    thisDefault = this.props.key1
    console.log('inside constructor')
    // alert(this.props.key1)
    if ( thisDefault != 100){
        alert('miracle')
    thisDefault = 1
  }


componentWillMount() {
    console.log('component mounted')
}

componentWillUnmount() {
    console.log('unmounted')
}

componentWillReceiveProps() {
    console.log('ghfdshg')
}



  render(){
    console.log('called from key')
    let data = null
     if(thisDefault == null) {
     data = (
      <div id = "journal" style={{ background: '#fff', padding: 24 , textAlign : 'center'}}>
       <Intro />
      </div>
      )
  }
  else{
  data = (  <div id = "journal" style={{ background: '#fff', padding: 24 , textAlign : 'center'}}>
       <h1> Hello </h1>
      </div>
      )
  }
    return( 
        <Content style={{ padding: '0 50px' }}>
        <Bread />
        <Slider />
    {data}
    </Content>

    )}}

    export default Cont

Upvotes: 0

Views: 988

Answers (1)

Talgat Saribayev
Talgat Saribayev

Reputation: 1938

The best way is update state and check it and render component.

class Head extends React.Component {
  state = {
    key: null
  }

  handleClick = ({key}) => {
    this.setState({key})
  }


  render(){
      const {key} = this.state;
  
      return( 
      <Header>
        <div className="logo" />
        {key && <Cont key1 ={key} />}
        <Menu
        onClick={ this.handleClick }>
        <Menu.Item key="1">Hungry Rides</Menu.Item>
        <Menu.Item key="2">Hiker's Diary</Menu.Item>
        <Menu.Item key="3">Hiking @ Hometown </Menu.Item>
      </Menu>
    </Header>
    )
  }
}

Upvotes: 2

Related Questions