tonyfat
tonyfat

Reputation: 331

How to pass a formik initialState value as a parameter to a function

I am using Formik within my React app and unsure how to pass a Formik value prop as a parameter into a function.

Let's say that I have the following Formik values:

"props": {
    "myJobName": "ABC"
 }

Within my button tag which all lives within my <Formik> and <Form> tags, I am trying to call setJobContent and pass in the values.myJobName

              <Button
                onClick={()=> {
                          setJobContent({values.myJobName})
                        }}
              />
              Click
              </Button> 

I also have the following function outside of my <Formik> and <Form> tags:

const setJobContent = (jobName) => {
 // do something 
 // return something
}

Unsure if this is possible and if so, would appreciate your help.

Upvotes: 0

Views: 2318

Answers (2)

Alex Ioannou
Alex Ioannou

Reputation: 11

Is this the behavior you wanted? https://codesandbox.io/live/jpr5fj3

export default function App() {

const setJobContent = (jobName) => {
    alert(jobName);
};



return (
  <div className="App">
    <Formik initialValues={{ myJobName: "test" }}>
      {({ values, handleChange }) => (
        <form>
          <input
            type="text"
            name="myJobName"
            onChange={handleChange}
            value={values.myJobName}
           />

          <em>{JSON.stringify(values, null, 2)}</em>
        <button
          type="button"
          onClick={() => setJobContent(values.myJobName)}
        >
          Submit
        </button>
      </form>
    )}
  </Formik>
</div>
);
}`

Upvotes: 1

Sahil Ardeshna
Sahil Ardeshna

Reputation: 184

if you want to get only "myJobName" in setJobContent function then you have to pass setJobContent(values.myJobName) like this.

Upvotes: 1

Related Questions