0

I am learning use Reduce function. I have text (1 sentence) with btn. When I click on btn. it shows me full text (5 sentences) + modal show up, when I click btn again text return to one sentence. It is toggle function. All is working. I want to add background color on modal. When text is full, modal with be green, if text is closed modal will be red. Modal show up from side and after 2sec modal go back. How can I add ternary conditional for modal? Thanks


 const reducer = (state, action) => {
    switch(action.type) {
    case 'TEXT2':
      return {...state, 
              readMore2: !state.readMore2,
              isModalOpen : true,
              modalContent: 'Toggle Text' } 
    default:
        throw new Error ('error')
   } 
 }

 const stateDefault = {
  readMore2 : false,
  modalContent:''
 }

function About() {
  return (
    <> 
       <AboutText/>
    </>
  )
}

const AboutText = () => {
  const [state, dispatch] = useReducer(reducer, stateDefault)

  const closeModal = () => {
        dispatch({type:'CLOSE_MODAL'})
  }

  return (
    <>
      <article >
        
      <p className="p2">
          {!state.readMore2 ? `${Text2.substring(0,45)} ...` : Text2 }
          { state.isModalOpen &&  <Modal closeModal={closeModal}  
           modalContent= {state.modalContent}/>}

          <button className='btn2'
                 onClick={()=> dispatch({type:'TEXT2'})}
              >
             {!state.readMore2 ?
                   'Read More' :
                    'Show Less'}               
         </button>
      </p><br/>
    </article>
    
    </>
  )
}

const Modal = ({modalContent, closeModal}) => {

  useEffect(()=> {
    setTimeout(() => {
       closeModal()
    }, 2000);
  })

  return (
    <>
    <div className='modal-box'>
       <h4 className='modal-text'>{modalContent}</h4>
    </div>
    </>
  )
}

export default About



pete
  • 45
  • 5
  • Unrelated to your question: you should clear the timeout in the return statement of the useEffect hook. – Shah Jun 24 '22 at 21:45

1 Answers1

0

’‘’ const [isModalOpen, setIsModalOpen] = React.useState(false) ‘’’

placed wherever you see fit in code: ‘’’ const styles = { modalOpen: {//styles}, modalClosed: {// styles} } ‘’’

and for usage with a ternary: ‘’’ isModalOpen ? styles.modalOpen : styles.modalClosed ‘’’

Shah
  • 2,126
  • 1
  • 16
  • 21