1
votes

Goal: To implement a Toast Message modal (using Functional Component) which will show or hide based on the props value (props.showToastModal) within the return of ToastModal component

Expected: Using props.showToastModal directly would determine if Toast appears

Actual: Modal does not appear based on props.showToastModal

Here's the code: Parent Component

class Datasets extends Component {
  constructor(props) {
    super(props)
    this.state = {
      showToastModal: false,
      toastModalText: ''
    }
  }

 toggleOff = () => {
    this.setState({ showToastModal: false, toastModalText: '' })
  }

 render() {
   {this.state.showToastModal && (
          <ToastModal
            showToastModal={this.state.showToastModal}
            toastModalText={this.state.toastModalText}
            toggleOff={this.toggleOff}
          />
   )}
 }
}

Child Component This works:

const ToastModal = (props) => {

  const isOpen = props.showToastModal

  return (
    <div className={`${css.feedbackModal} ${isOpen ? css.show : css.hide}`}>
      {props.toastModalText}
      <i
        className={`bx bx-x`}
        onClick={() => props.toggleOff()}
      />
    </div>
  )
}

export default ToastModal

But this doesn't (using the props value directly):

const ToastModal = (props) => {

  return (
    <div className={`${css.feedbackModal} ${props.showToastModal ? css.show : css.hide}`}>
      {props.toastModalText}
      <i
        className={`bx bx-x`}
        onClick={() => props.toggleOff()}
      />
    </div>
  )
}

export default ToastModal

Using a const isOpen = props.showToastModal works as expected instead. I am confused why this happens. Is this is a React Lifecycle issue, or a case where it is bad practice to use props values which may be updated during the render?

1
From glancing at your code there is no difference in functionality. Are you confident nothing else has changed? Can you provide a Codesandbox example or update and use an inline stack snippet (there's support for React)?skovy
Second what @skovy says, from what you posted all you did was condense some logic. Yes to sharing a codesandbox that replicates your issue.Drew Reese

1 Answers

0
votes

Please try destructuring objects

const ToastModal = ({ showToastModal, toggleOff }) => {

  return (
    <div className={`${css.feedbackModal} ${showToastModal ? css.show : css.hide}`}>
      {props.toastModalText}
      <i
        className={`bx bx-x`}
        onClick={toggleOff}
      />
    </div>
  )
}

export default ToastModal