How to reset text field React Formik?

Viewed 30

I have a container component that works with Redux, in it I determined the state of the text field and throw it into the form component that works with Formik

But I have such a problem that after clicking the button, the text field is not cleared

How do I fix this ? I've seen a lot about resetForm() from Formik, but I can't work with it

TaskInput.jsx

export const TaskInput = ({ value, onChange, onAdd }) => {
  const formik = useFormik({
    initialValues: {
      text: value,
    },
  })

  return (
    <Container>
      <Formik>
        <FormWrapper onSubmit={onAdd}>
          <Input
            id="task"
            type="text"
            placeholder="Add a task"
            value={formik.text}
            onChange={onChange}
          />
          <AddButton type="submit">Add</AddButton>
        </FormWrapper>
      </Formik>
    </Container>
  )
}

Task.jsx(component container)

class Task extends PureComponent {
  constructor(props) {
    super(props)

    this.state = {
      taskText: '',
    }
  }

  handleInputChange = e => {
    this.setState({
      taskText: e.target.value,
    })
  }

  handleAddTask = () => {
    const { taskText } = this.state
    const { addTask } = this.props
    addTask(uuidv4(), taskText, false)
    this.setState({
      taskText: '',
    })
  }

  render() {
    const { taskText } = this.state
    return (
      <>
        <TaskInput
          onAdd={this.handleAddTask}
          onChange={this.handleInputChange}
          value={taskText}
        />
...
      </>
    )
  }
}

const mapStateToProps = ({ tasks }) => {
  return {
    tasks,
  }
}

export default connect(mapStateToProps, {
  addTask,
  removeTask,
  completeTask,
  editTask,
})(Task)
1 Answers

Solution

export const TaskInput = ({ value, onChange, onAdd }) => {
  const inputRef = useRef(null)
  const formik = useFormik({
    initialValues: {
      text: value,
    },
  })

  const onSubmit = () => {
    onAdd(),
    inputRef.current.value = ''
  }

  return (
    <Container>
      <Formik>
        <FormWrapper onSubmit={onSubmit}>
          <Input
            ref={inputRef}
            id="task"
            type="text"
            placeholder="Add a task"
            value={formik.text}
            onChange={onChange}
          />
          <AddButton type="submit">Add</AddButton>
        </FormWrapper>
      </Formik>
    </Container>
  )
}
Related