Skip to content

Instantly share code, notes, and snippets.

@yasudacloud
Created September 29, 2022 17:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yasudacloud/dc60cd862100d467131e5e0517f2179b to your computer and use it in GitHub Desktop.
Save yasudacloud/dc60cd862100d467131e5e0517f2179b to your computer and use it in GitHub Desktop.
plugin/admin/src/components/PostCode/index.tsx
// plugin/admin/src/components/PostCode/index.tsx
import * as React from 'react'
import {TextInput} from '@strapi/design-system/TextInput';
import {useIntl} from 'react-intl';
import styled from 'styled-components'
import {useState} from "react";
interface Props {
intlLabel: any
onChange: (any) => void
attribute: any
name: string
description?: string
disabled: boolean
error?: string
labelAction: () => void
required?: boolean
value: string,
}
const InputLabel = styled.p`
font-size: 0.75rem;
font-weight: 600;
line-height: 1.33;
`
const ErrorMessage = styled(InputLabel)`
color: #ff0000;
margin: 2px 0;
`
const isNumberOnly = (value: string) => {
return value === '' || !!value.match(/^\d+$/)
}
const PostCode = (props: Props) => {
const {formatMessage} = useIntl();
const [postCode1, setPostCode1] = useState(props.value ? props.value.substring(0, 3) : '')
const [postCode2, setPostCode2] = useState(props.value ? props.value.substring(3, 7) : '')
const setValue = (p1, p2) => {
props.onChange({
target: {
name: props.name,
value: `${p1}${p2}`,
type: props.attribute.type
}
})
}
return (
<>
<InputLabel>{formatMessage(props.intlLabel)}</InputLabel>
<div
style={{display: 'flex'}}
>
<TextInput
placeholder="000"
label={' '}
name={`${props.name}1`}
maxLength={3}
onChange={e => {
if (isNumberOnly(e.target.value)) {
setPostCode1(e.target.value)
setValue(e.target.value, postCode2)
}
}}
value={postCode1}
/>
<span style={{alignSelf: 'center'}}>&nbsp;{'-'}&nbsp;</span>
<TextInput
placeholder="0000"
label={' '}
maxLength={4}
name={`${props.name}2`}
onChange={e => {
if (isNumberOnly(e.target.value)) {
setPostCode2(e.target.value)
setValue(postCode1, e.target.value)
}
}}
value={postCode2}
/>
</div>
{props.error && <ErrorMessage>{props.error}</ErrorMessage>}
</>
)
}
PostCode.defaultProps = {
description: null,
disabled: false,
error: null,
labelAction: null,
required: false,
value: ''
}
export default PostCode
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment