Updating external states to update input value and form value with React & Formik

Viewed 310

enter image description here

This is basically the workflow of this form I am trying to implement:

  1. Input where user can type in his own text input.

  2. User may select one of the three buttons above, where upon user's click, it will render the input value as well as form's state value.

Below is how I thought of implementing such feature:

(1) I would first create input to be received as component for Formik field. (2) So, upon change inside the input, input will automatically update the state. (3) Then I have buttons where upon each click I store user's input into my own state.

First I would create a render function where upon set of random words, I would render each of them out with "onclick attached to it"

    const renderButtons = () => {
        return wordList.map((word) => {
            return (
                <SquareButton
                    onClick={() => handleClick(word)}
                    text={word}
                    color='secondary'
                    size='sm'
                    shadow={true}
                    key={word}
                    fullWidth={true}
                />
            );
        });
    };

(2) Upon clicking each of the button I would save them in local state.

const [selectedWord, setSelectedWord] = useState("");
    const handleClick = (word) => {
        setSelectedWord(word);
    };

(3) Now, below is the acutal input that saves the data to its initial value. I will receive the state from above component so that the form knows, 'what's clicked data'


const FormikInput = ({ label, name, selectedWord, ...rest }) => {
    const [prevWord, updateWord] = useState(selectedWord);

    return (
        <div className='form-control'>
            <label htmlFor={name} />
            <Field
                component={Input}
                id={name}
                name={name}
                selectedWord={selectedWord}
                {...rest}
            >
                {/* {({ form, field }) => {
                    return (
                        <input
                            onChange={(e) => updateWord(e.target.value)}
                            value={prevWord}
                        />
                    );
                }} */}
            </Field>

            <div className='formik__error'>
                <ErrorMessage name={name} component={FormikError} />
            </div>
        </div>
    );
};

Now, here's my question.

(1) I tried putting state data into input's value, but that will disable the input from user entering their own value. How can I achieve both using Formik?

(2) How do I gather other external state values and incorporate into the form upon certain action from different components? (like the previous one)

Please advise.

0 Answers
Related