简体   繁体   中英

Having trouble with ReactJS button functionality

I have an array of categories, each category opens to a list of options. I am creating a button that once you click it should close the current category and open the next. The category and current index are passed as props from surveyForm, I can't figure out why I can't increment to the next index and how I would tell it to open the next category.

When I console log the c_index, I get the right index, when I console log the category I get [object, object]

Right now my openNext button only toggles the current category closed.... please help!

const SPQuestion = ({ category, c_index }) => {
  const [isOpen, setIsOpen] = useState(false);
  const [index, setIndex] = useState(0);

  const diversitySurvey = useSelector(state => state.appData.diversitySurvey)
  const categories = diversitySurvey.categories

  const toggle = () => setIsOpen(!isOpen);

  const openNext = (c_index) => {
    if( c_index === categories.length - 1){
      toggle()
    } else {
      toggle()
      setIndex(index + 1) // I also tried c_index++ and categories[c_index]++
      setIsOpen(true)
    }
  }

  return (
    <div key={category.title} className="sp-question active">
      <Button onClick={toggle} className={`${category.hasFollowUps ? 'parent-category' : ''}`} ><legend>{category.title}</legend></Button>
      <div border border-primary>
            <Collapse isOpen={isOpen}>
              <Field model={`appData.diversitySurvey.categories[${c_index}].selectedValue`} >
                <div>
                  <span className="sp-instructions">
                    {category.select === 'one' && 'Select One'}
                    {category.select === 'many' && 'Select all that apply'}
                  </span>
                  <Row>
                    <Col className="py-2 rounded foo" sm="12">
                    <Row sm="2" xl="3">
                      {category.options.map((option, o_index) => {
                        return (
                          <SPOption
                            c_index={c_index}
                            o_index={o_index}
                            option={option}
                            select={category.select}
                          />

                        )
                      }
                      )}
                      </Row>
                      <div id="fixme" className="d-flex flex-row-reverse">
                        <Button active className="float-right" style={{backgroundColor: '#70d9b8'}} size="sm" onClick={() => openNext(c_index)} >Next</Button>
                      </div>
                    </Col>
                  </Row>

                </div>
              </Field>
            </Collapse>
      </div>
    </div>
  )
}
export const SurveyForm = ({ handleSubmit, survey }) => {
  const diversitySurvey = useSelector(State => State.appData.diversitySurvey)


  const errorMessage = useSelector(state => state.errorMessage)
  const dispatch = useDispatch()


  return (
    <Form model="appData" onSubmit={handleSubmit} >
      <Row>
        <Col md="12" className="title"><h1>{diversitySurvey.title}</h1></Col>
      </Row>
      <Row>
        <Col md="12" className="questions">
          {diversitySurvey.categories.map((category, c_index) => {
              return (
                <SPQuestion category={category} c_index={c_index} modelPrefix="appData.diversitySurvey" />
              )
            })}
          <div className="sp-button-container">
            <Button className="sp-submit" onClick={() => dispatch(submitSurvey(diversitySurvey))}>Submit</Button>
          </div>
          {errorMessage &&
            <Alert className="sp-fetch-error" color="danger">
              <p className="text-danger">{errorMessage}</p>
            </Alert>
          }

        </Col>
      </Row>
    </Form>
  )
}




I think you should add a new state, selected index state , in the parent component. Then add a selected index props and a function props to set value in it in SPQuestion component and use the new props to compare whether the collapse is open or not.

const SPQuestion = ({ category, c_index ,s_index,setSelectedIndex}) => {
  const toggle = () => {
    if( c_index == s_index){
      setSelectedIndex(-1);
    }else{
    setSelectedIndex(c_index)
    }
  }

  const openNext = () => {
    if( c_index < categories.length){
      setSelectedIndex(c_index + 1);
    } 
  }

 
  <Collapse isOpen={c_index === s_index}>     
}

Then in parent component:

 const [index, setIndex] = useState(-1);

 <SPQuestion category={category} c_index={c_index} s_index={index} setSelectedIndex={setIndex} modelPrefix="appData.diversitySurvey" />

I haven't tested it yet so if you can provide sandbox, please do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM