Johnny88520
Johnny88520

Reputation: 157

how to show/hide on the same component in Reactjs

I'm newbie in React, and I try to hide an image after I click the same image and then show the dropdown component from other folder. How do I do that?

I'm current stuck in not being able to hide the same picture and it shows the same picture at different spot.

Or is there better way to do it?

Below is the code

import React from 'react';
import mind_zebra from '../../images/MindScribe-zebra.png';
import dropdown from '../DropDown/DropDown.js';
import './entry.css';

class Entry extends React.Component {

  state = { hideZebraPic : false};

  onClickHandler = () => {
    this.setState( prev => ({ hideZebraPic : !prev.hideZebraPic }));
  };

  render() {
    return (
      <div>
        <img src={mind_zebra} onClick={this.onClickHandler} className="MindZebraPic" alt="zebra"/>
        {this.state.hideZebraPic ? <Entry /> : null}
      </div>
    );
  }
}

Upvotes: 1

Views: 45

Answers (1)

sarneeh
sarneeh

Reputation: 1388

In your code you are always rendering the image. There is no condition to not render it in your render function.

If I'm understanding properly what you want to achieve, the right code for the render function would be:

render() {
  if (this.state.hideZebraPic) {
    return <Dropdown />;
  } else {
    return <img src={mind_zebra} onClick={this.onClickHandler} />;
  }
}

It could be also written like this:

render() {
  return (
    <div>
      {!this.state.hideZebraPic && (
        <img src={mind_zebra} onClick={this.onClickHandler} />
      )}
      {this.state.hideZebraPic && <Dropdown />}
    </div>
  );
}

Upvotes: 1

Related Questions