I have a component with an input field and checkbox. As it stands the checkbox disables the input field and clears any validation errors. What I'm trying to do is create additional functionality that if someone unchecks that box and the input becomes active again, a validation will run and once again prompt the user to enter an email. I have a code sandbox here for example and my full component listed below
import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import {
Col, Row, Icon, Input, Tooltip
} from 'antd'
import Checkbox from '../elements/Checkbox'
import Markup from '../core/Markup'
function validateEmail(value) {
const errors = {}
if (value === '') {
errors.email = 'Email address is required'
} else if (!/\S+@\S+\.\S+/.test(value)) {
errors.email = 'Email address is invalid'
}
return errors
}
const CustomerDetails = ({ customer }) => {
const { contact = {}, account = {}, site = {} } = customer || {}
const [disableInput, setDisableInput] = React.useState(false)
const [errors, setErrors] = React.useState({})
const [inputValue, setInputValue] = React.useState(contact.email)
function onBlur(e) {
setErrors(validateEmail(e.target.value))
}
function clearInput() {
setInputValue(' ')
}
function handleInputChange(event) {
setInputValue(event.target.value)
}
function CheckboxClick() {
if (!disableInput) {
clearInput()
}
setDisableInput(prevValue => !prevValue)
setError({})
}
return (
<Container>
<Row>
<Col span={10}>
<h4>
PRIMARY CONTACT EMAIL
</h4>
</Col>
</Row>
<Row>
<Col span={8}>
<StyledInput
value={inputValue}
onChange={handleInputChange}
disabled={disableInput}
onBlur={onBlur}
isError={!!errors.email}
/>
{errors.email && <ErrorDiv>{errors.email}</ErrorDiv>}
</Col>
<Col span={2} />
<Col span={8}>
<StyledCheckbox
value={disableInput}
onChange={CheckboxClick}
/> EMAIL
OPT OUT{' '}
</Col>
</Row>
</Container>
)
}
const Container = styled.div`
text-align: left;
`
const StyledCheckbox = styled(Checkbox)`
&&& {
background: white;
input + span {
width: 35px;
height: 35px;
border: 2px solid ${({ theme }) => theme.colors.black};
}
input + span:after {
width: 12.5px;
height: 20px;
}
input:focus + span {
width: 35px;
height: 35px;
}
}
`
const ErrorInput = ({ isError, ...remainingProps }) => (
<Input {...remainingProps} />
)
ErrorInput.propTypes = {
isError: PropTypes.bool
}
const StyledInput = styled(Input)`
max-width: 100%;
background: white;
&&& {
border: 2px solid ${props => (props.isError ? '#d11314' : 'black')};
border-radius: 0px;
height: 35px;
}
`
const ErrorDiv = styled.div`
color: #d11314;
`
export default CustomerDetails