React implements the expansion and collapse function of complex search forms

React implements the expansion and collapse function of complex search forms

Give time time and let the past go.

In the previous section, we wrote about the [Search] form, as well as the query and reset functions. This section provides an overview of query forms that require expansion and collapse effects, mainly involving front-end style knowledge.

The style effect is as follows:

Idea: Define two components renderAdvancedForm and renderSimpleForm in the Search component. RenderSimpleForm has only five query options, while renderAdvancedForm contains all search options. Click the 'Expand' or 'Collapse' button and call onClick={toggleForm} to switch the form display style.

1. Write renderSimpleForm and renderAdvancedForm

Use Col and Row to divide the rows into blocks, and pay attention to adding a click event for the expansion button.

 const renderSimpleForm = useMemo(() => {
    const { getFieldDecorator } = form
    const { query } = getLocation()
    return (
      <Form layout="inline">
        <Row>
          <Col md={4} sm={24}>
            <FormItem label="">...</FormItem>
          </Col>
          <Col md={4} sm={24}>
            <FormItem label="">...</FormItem>
          </Col>
          <Col md={4} sm={24}>
            <FormItem label="">...</FormItem>
          </Col>
          <Col md={4} sm={24}>
            <FormItem label="">...</FormItem>
          </Col>
          <Col md={4} sm={24}>
            <FormItem label="">...</FormItem>
          </Col>
          <Col md={4} sm={24} style={{ textAlign: 'right' }}>
            <a
              onClick={toggleForm}
              style={{ marginRight: '15px' }}
              className={styles.a}
            >
              Expand <Icon type="down" />
            </a>
            <Button onClick={handleSearch} className={'searchBtn'}>
              <img src={search} alt="" />
              Query</Button>
            <Button onClick={handleFormReset} className={'resetBtn'}>
              <img src={reset} alt="" />
              Reset</Button>
          </Col>
        </Row>
      </Form>
    )
  }, [form, handleFormReset, handleSearch, toggleForm])

Similarly, you need to use Rol and Row to set two rows, leave a close button in the corresponding position, and add a click function for the close button

const renderAdvancedForm = useMemo(() => {
    const { getFieldDecorator, getFieldValue } = form
    const { query } = getLocation()
    return (
      <Form layout="inline">
        <Row style={{ marginBottom: '20px' }}>
          <Col md={4} sm={24}><FormItem label="">...</FormItem></Col>
          <Col md={4} sm={24}><FormItem label="">...</FormItem></Col>
          <Col md={4} sm={24}><FormItem label="">...</FormItem></Col>
          <Col md={4} sm={24}><FormItem label="">...</FormItem></Col>
          <Col md={4} sm={24}><FormItem label="">...</FormItem></Col>
          <Col md={4} sm={24} style={{ textAlign: 'right' }}>
            <a
              onClick={toggleForm}
              style={{ marginRight: '15px' }}
              className={styles.a}
            >
              Collapse<Icon type="up" />
            </a>
            <Button onClick={handleSearch} className={'searchBtn'}>
              <img src={search} alt="" />
              Query</Button>
            <Button onClick={handleFormReset} className={'resetBtn'}>
              <img src={reset} alt="" />
              Reset</Button>
          </Col>
        </Row>
        <Row>
          <Col md={4} sm={24}><FormItem label="">...</FormItem></Col>
          <Col md={4} sm={24}><FormItem label="">...</FormItem></Col>
          <Col md={4} sm={24}><FormItem label="">...</FormItem></Col>
          <Col md={4} sm={24}><FormItem label="">...</FormItem></Col>
        </Row>
      </Form>
    )
  }, [form, handleFormReset, handleSearch, time1, time2, toggleForm])

2. Add toggleForm function to switch between 'expand' and 'collapse'

const toggleForm = useCallback(() => {
    setExpandForm(!expandForm)
  }, [expandForm])

3. Render the form effect in the search component as needed

return (
    <Card bordered={false}>
      <div className={styles.search}>
        {expandForm ? renderAdvancedForm : renderSimpleForm}
      </div>
    </Card>
  )

4. Attached is the complete search component code

const Search: any = Form.create()(function({ form, init }: any) {
  const { validateFields } = form
  const [expandForm, setExpandForm] = useState(false)
  const [time11, settime11] = useState('')
  const [time21, settime21] = useState('')
  const [time1, settime1] = useState(moment().format('YYYY-MM-DD'))
  const [time2, settime2] = useState(moment().format('YYYY-MM-DD'))
  const handleSearch = useCallback(() => {
    validateFields((err: any, data: any) => {
      pushPath({
        query: {
          ...data,
          pageNum: 1,
          orderTimeStart: time11,
          orderTimeEnd: time21,
          orderNumber: data.orderNumber.replace(/\s+/g, ''),
          experimentName: data.experimentName.replace(/\s+/g, ''),
          userName: data.userName.replace(/\s+/g, ''),
          mobile: data.mobile.replace(/\s+/g, ''),
          priceLow: data.priceLow.replace(/\s+/g, ''),
          priceHigh: data.priceHigh.replace(/\s+/g, '')
        }
      })
      init()
    })
  }, [init, time11, time21, validateFields])
  const handleFormReset = useCallback(() => {
    clearPath()
    pushPath({
      query: { pageSize: 10, pageNum: 1 }
    })
    init()
    form.resetFields()
  }, [form, init])
  const toggleForm = useCallback(() => {
    setExpandForm(!expandForm)
  }, [expandForm])
  const renderSimpleForm = useMemo(() => {
    const { getFieldDecorator } = form
    const { query } = getLocation()
    return (
      <Form layout="inline">
        <Row>
          <Col md={4} sm={24}>
            <FormItem label="">
              {getFieldDecorator('orderNumber', {
                initialValue: query.name || ''
              })(<Input placeholder="Requirement number" />)}
            </FormItem>
          </Col>
          <Col md={4} sm={24}>
            <FormItem label="">
              {getFieldDecorator('experimentName', {
                initialValue: query.name || ''
              })(<Input placeholder="Requirement name" />)}
            </FormItem>
          </Col>
          <Col md={4} sm={24}>
            <FormItem label="">
              {getFieldDecorator('userName', {
                initialValue: query.name || ''
              })(<Input placeholder="Username" />)}
            </FormItem>
          </Col>
          <Col md={4} sm={24}>
            <FormItem label="">
              {getFieldDecorator('mobile', { initialValue: query.name || '' })(
                <Input placeholder="Phone number" />
              )}
            </FormItem>
          </Col>
          <Col md={4} sm={24}>
            <FormItem label="">
              {getFieldDecorator('status', {
                initialValue:
                  query.type === undefined ? '' : query.type.toString()
              })(
                <Select>
                  <Option value={''} disabled>
                    {' '}
                    Experimental Status {' '}
                  </Option>
                  {testStatus.map((v: any) => (
                    <Option key={v.key} value={v.key}>
                      {v.value}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
 
          <Col md={4} sm={24} style={{ textAlign: 'right' }}>
            <a
              onClick={toggleForm}
              style={{ marginRight: '15px' }}
              className={styles.a}
            >
              Expand <Icon type="down" />
            </a>
            <Button onClick={handleSearch} className={'searchBtn'}>
              <img src={search} alt="" />
              Query</Button>
            <Button onClick={handleFormReset} className={'resetBtn'}>
              <img src={reset} alt="" />
              Reset</Button>
          </Col>
        </Row>
      </Form>
    )
  }, [form, handleFormReset, handleSearch, toggleForm])
  const renderAdvancedForm = useMemo(() => {
    const { getFieldDecorator, getFieldValue } = form
    const { query } = getLocation()
 
    function disabledDate1(current: any) {
      return current && current > time2
    }
    function disabledDate2(current: any) {
      return current && current < time1
    }
    function change1(date: any, dateString: any) {
      settime1(date)
      settime11(dateString)
    }
    function change2(date: any, dateString: any) {
      settime2(date)
      settime21(dateString)
    }
    const dataValidate = (rule: any, value: any, callback: any) => {
      if (value && parseInt(value) > parseInt(getFieldValue('priceHigh'))) {
        callback('cannot be higher than the maximum value')
      } else if (
        value &&
        parseInt(value) < parseInt(getFieldValue('priceLow'))
      ) {
        callback('cannot be lower than the minimum value')
      } else {
        callback()
      }
    }
    return (
      <Form layout="inline">
        <Row style={{ marginBottom: '20px' }}>
          <Col md={4} sm={24}>
            <FormItem label="">
              {getFieldDecorator('orderNumber', {
                initialValue: query.name || ''
              })(<Input placeholder="Requirement number" />)}
            </FormItem>
          </Col>
          <Col md={4} sm={24}>
            <FormItem label="">
              {getFieldDecorator('experimentName', {
                initialValue: query.name || ''
              })(<Input placeholder="Requirement name" />)}
            </FormItem>
          </Col>
          <Col md={4} sm={24}>
            <FormItem label="">
              {getFieldDecorator('userName', {
                initialValue: query.name || ''
              })(<Input placeholder="Username" />)}
            </FormItem>
          </Col>
          <Col md={4} sm={24}>
            <FormItem label="">
              {getFieldDecorator('mobile', { initialValue: query.name || '' })(
                <Input placeholder="Phone number" />
              )}
            </FormItem>
          </Col>
          <Col md={4} sm={24}>
            <FormItem label="">
              {getFieldDecorator('status', {
                initialValue:
                  query.type === undefined ? '' : query.type.toString()
              })(
                <Select>
                  <Option value={''}> Experimental status</Option>
                  {testStatus.map((v: any) => (
                    <Option key={v.key} value={v.key}>
                      {v.value}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
 
          <Col md={4} sm={24} style={{ textAlign: 'right' }}>
            <a
              onClick={toggleForm}
              style={{ marginRight: '15px' }}
              className={styles.a}
            >
              Collapse<Icon type="up" />
            </a>
            <Button onClick={handleSearch} className={'searchBtn'}>
              <img src={search} alt="" />
              Query</Button>
            <Button onClick={handleFormReset} className={'resetBtn'}>
              <img src={reset} alt="" />
              Reset</Button>
          </Col>
        </Row>
        <Row>
          <Col md={4} sm={24}>
            <FormItem label="">
              {getFieldDecorator('priceLow', {
                initialValue: query.name || '',
                rules: [{ validator: dataValidate }]
              })(<Input placeholder="Total price range" />)}
            </FormItem>
          </Col>
          <Col md={4} sm={24}>
            <FormItem label="">
              {getFieldDecorator('priceHigh', {
                initialValue: query.name || '',
                rules: [{ validator: dataValidate }]
              })(<Input placeholder="Total price range" />)}
            </FormItem>
          </Col>
          <Col md={4} sm={24}>
            <FormItem label="">
              {getFieldDecorator('orderTimeStart', {
                initialValue: query.name || ''
              })(
                <DatePicker
                  onChange={change1}
                  disabledDate={disabledDate1}
                  placeholder="Order time"
                />
              )}
            </FormItem>
          </Col>
          <Col md={4} sm={24}>
            <FormItem label="">
              {getFieldDecorator('orderTimeEnd', {
                initialValue: query.name || ''
              })(
                <DatePicker
                  onChange={change2}
                  disabledDate={disabledDate2}
                  placeholder="Order time"
                />
              )}
            </FormItem>
          </Col>
        </Row>
      </Form>
    )
  }, [form, handleFormReset, handleSearch, time1, time2, toggleForm])
 
  return (
    <Card bordered={false}>
      <div className={styles.search}>
        {expandForm ? renderAdvancedForm : renderSimpleForm}
      </div>
    </Card>
  )
})

This concludes this article about implementing the expand-collapse function of complex search forms in React. For more relevant React form expansion and collapse content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Simpler implementation in projects such as vue and react Expand and collapse more examples of effects

<<:  Talk about implicit conversion in MySQL

>>:  A brief discussion on the differences between FTP, FTPS and SFTP

Recommend

The use of setState in React and the use of synchronous and asynchronous

In react, if you modify the state directly using ...

Methods of adaptive web design (good access experience on mobile phones)

1. Add the viewport tag to the HTML header. At th...

Vue realizes simple effect of running light

This article shares the specific code of Vue to a...

Implementation of tomcat image created with dockerfile based on alpine

1. Download the alpine image [root@docker43 ~]# d...

A simple method to implement Linux timed log deletion

Introduction Linux is a system that can automatic...

XHTML Web Page Tutorial

<br />This article is mainly to let beginner...

Detailed installation instructions for the cloud server pagoda panel

Table of contents 0x01. Install the Pagoda Panel ...

Detailed explanation of 10 common HTTP status codes

The HTTP status code is a 3-digit code used to in...

How to generate a free certificate using openssl

1: What is openssl? What is its function? What is...

Vue two-choice tab bar switching new approach

Problem Description When we are working on a proj...

Vue implements the full selection function

This article example shares the specific code of ...

Install JDK8 in rpm mode on CentOS7

After CentOS 7 is successfully installed, OpenJDK...