Gilad Adar
Gilad Adar

Reputation: 193

react JS render a component after a click

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>
    )
  }
}

Upvotes: 2

Views: 8353

Answers (1)

m-a-r-c-e-l-i-n-o
m-a-r-c-e-l-i-n-o

Reputation: 2672

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!

Upvotes: 6

Related Questions