2

I'm using React and when a user clicks on the <li> tag, the popup method is fired, but the component inside the method is not shown, the popup component does not get fired, why is that?

  export default class Main extends React.Component {
  constructor(props) {
    super(props);
  }
  popup(value) {
    console.log('fired ok');
    //call popup component
    <Popup value={value} />
  }
  render() {
    return (
      <ul>
        <li key={0} onClick={() => this.popup(value)} />
      </ul>
    )
  }
}

export default class Popup extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    console.log('this is not fired');
    const { value } = this.props;

    return (
      <div class="popup">
        <p>{value}</p>
      </div>
    )
  }
}

1 Answer 1

6

You would need to actually render the Popup element, something along the lines of:

export default class Main extends React.Component {
  constructor(props) {
    super(props);
    // save the popup state
    this.state = {
        visible: false, // initially set it to be hidden
        value: '' // and its content to be empty
    };
  }
  popup(value) {
    console.log('fired ok');
    this.setState({
      visible: true, // set it to be visible
      value: value // and its content to be the value
    })
  }
  render() {
    // conditionally render the popup element based on current state
    const popup = (this.state.visible ? <Popup value={this.state.value} /> : null);
    return (
      <ul>
        {popup} 
        <li key={0} onClick={() => this.popup('Hello World')}>Click Me!</li>
      </ul>
    )
  }
}

Here's a fiddle of it in action. Click on the black "Click Me!" text.

I hope that helps!

Sign up to request clarification or add additional context in comments.

1 Comment

That is exactly what is was thinking to do, thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.