mikayiri
mikayiri

Reputation: 39

How to fix error of hiding and showing <div> in React

I am working on a project and i want to display a hidden <div> below another <div> element using an event handler but when i click the icon that is meant to display the div, the whole page becomes blank

This is image I want:

enter image description here

This is what i get The output I have tried to check through the internet for some places where i could get the solution. Well i found something similar to what i had done but the error still happens for me.

class PostItTeaser extends Component {
  state = {
    postIt: false,
    moreIt: false,
  }

  togglePostIt = e => {
    e ? e.preventDefault() : null
    this.setState({ postIt: !this.state.postIt })
  }

  _toggle = e => {
    e ? e.preventDefault() : null
    this.setState({
      moreIt: !this.state.moreIt,
    })
  }

  Child = () => <div className="modal">Hello, World!</div>

  render() {
    let { postIt } = this.state
    let { moreIt } = this.state
    let {
      type,
      group,
      disabled,
      session: { id, username },
    } = this.props

    return (
      <div>
        <div
          className="post_it inst"
          style={{ marginBottom: type == 'group' && 10 }}
        >
          <img src={`/users/${id}/avatar.jpg`} alt="Your avatar" />
          <div className="post_teaser">
            <span
              className="p_whats_new"
              onClick={disabled ? null : this.togglePostIt}
            >
              What's new with you, @{username}? #cool
            </span>
            <span className="m_m_exp" data-tip="More" onClick={this._toggle}>
              <MaterialIcon icon="expand_more" />
            </span>
          </div>
        </div>
        {moreIt && <Child />}

        {postIt && (
          <PostIt back={this.togglePostIt} type={type} group={group} />
        )}
      </div>
    )
  }
}

Upvotes: 1

Views: 212

Answers (1)

Fredrik
Fredrik

Reputation: 5108

From skimming through the code I believe you need to bind the scope, since the function you're calling is using this.setState, it needs this to be the react component, not the event you're listening to:

onClick={this._toggle.bind(this)}

You can also bind the functions scope in the constructor. Or, a less memory performant & ugly way:

onClick={() => { this._toggle(); } }

Upvotes: 1

Related Questions