Hide component onClick using state with React

707 views Asked by At

I'm trying to hide StickyFooterDynamic onCLick. I've managed to hide it with css but I'd like to use React's state to completely remove it from the DOM onClick. Does anyone have a suggestion on how to do this? ES6 way.

class StickyFooterDynamic extends React.Component {
constructor(props) {
super(props);

this.state = {
  visible: true,
}
}

onClick() {
this.setState(prevState => ({
  visible: !prevState.visible,
}))
}

render() {

if (!this.state.visible) {
  return null
}

const { url, service } = this.props;

return (
  <StickyFooter>
    <div className='sticky-footer-dynamic-wrapper'>
      <div className='main-content'>
        <div className='copy-wrapper'>
          <img className='sticky-footer-dynamic-img' alt='Repair Icon' src={iconRepair} />
          <h3 className='sticky-footer-copy'>Want a free quote for {service}?</h3>
        </div>
        <a className='sticky-footer-dynamic-btn btn' href={url}>GET<i className="right-arrow"></i></a>
        <a href='#' className='sticky-footer-close' onClick={this.onClick}></a>
      </div>
    </div>
  </StickyFooter>
);
}
}

export default StickyFooterDynamic;
1

There are 1 answers

11
Hemerson Carlin On BEST ANSWER

You can toggle inner state and return null instead:

class StickyFooterDynamic extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      visible: true,
    }

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

  onClick(event) {
    event.preventDefault()

    this.setState(prevState => ({
      visible: !prevState.visible,
    }))
  }

  render() {
    if (!this.state.visible) {
      return null
    }

    const { url, service } = this.props

    return (
      <StickyFooter>
        ...
        <a href="#" className='sticky-footer-close' onClick={this.onClick}></a>
      </StickyFooter>
    )
  }
}