index.tsx 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import { makeStyles, Button, TextField, Typography } from '@material-ui/core'
  2. import React, { useState } from 'react';
  3. import { useDispatch } from 'react-redux';
  4. import { asyncAddContact } from '../../../../redux/contacts/operations'
  5. import ToolBar from './ToolBar';
  6. const useStyles = makeStyles({
  7. container: {
  8. display: 'flex',
  9. alignItems: 'center',
  10. alignContent:'center',
  11. flexDirection: 'column',
  12. width: 350,
  13. margin: '0 auto',
  14. paddingBottom: 24,
  15. },
  16. title: {
  17. marginBottom: 20,
  18. textAlign: 'center',
  19. },
  20. buttonNext: {
  21. marginTop: 20,
  22. height: 50,
  23. color: '#f8f8f8',
  24. backgroundColor:'#1d74c5',
  25. },
  26. textField: {
  27. marginBottom:20
  28. }
  29. })
  30. interface IAddContact {
  31. setSelectedIndex: React.Dispatch<React.SetStateAction<number | null>>,
  32. handleClick: () => void
  33. }
  34. const AddContact = ({setSelectedIndex,handleClick}:IAddContact) => {
  35. const classes = useStyles()
  36. const dispatch = useDispatch()
  37. const [number, setNumber] = useState<string>('')
  38. const handleTextField = (e: React.ChangeEvent<HTMLInputElement>) => {
  39. const value = e.target.value.split(' ').join('').trim()
  40. setNumber(value)
  41. }
  42. const handleAddContact = async () => {
  43. dispatch(asyncAddContact(number))
  44. setNumber('')
  45. setSelectedIndex(1)
  46. }
  47. const isValidNumber = () => {
  48. if (number.length < 13 || number.length > 13) return false
  49. if(number.slice(0,1) === '+') return true
  50. return true
  51. }
  52. const handlePressEnter = (e: React.KeyboardEvent<HTMLDivElement>) => {
  53. if(e.code === 'Enter' && isValidNumber()) handleAddContact()
  54. }
  55. return (
  56. <>
  57. <ToolBar handleClick={handleClick}/>
  58. <div onKeyDown={handlePressEnter} className={classes.container} >
  59. <Typography
  60. className={classes.title}
  61. variant="h5"
  62. color="initial">
  63. Add new contact
  64. </Typography>
  65. <TextField
  66. id="number"
  67. name='NUMBER'
  68. label="Write down a number,+ is requirement"
  69. value={number}
  70. fullWidth
  71. variant='outlined'
  72. onChange={handleTextField}
  73. className={classes.textField}
  74. required
  75. />
  76. {isValidNumber() &&
  77. <Button
  78. onClick={handleAddContact}
  79. className={classes.buttonNext}
  80. color='primary'
  81. variant="contained"
  82. fullWidth
  83. > ADD
  84. </Button>}
  85. </div>
  86. </>
  87. );
  88. };
  89. export default AddContact;