Ying
Ying

Reputation: 299

How to pass one prop as a variable to another prop in React?

May I know how to pass a prop as a variable to another prop passed to the child component?

So in parent component I use pass two props "name" and "formProps" to a child like this:

<FormField name="id" formProps={formProps} />
<FormField name="amount" formProps={formProps} />

In className of the Child Component, I want to make the {props.name} as a variable to the {props.formprops.errors}, but I don't know how to.

I want it be like this:

When "name" prop equals to "id",

props.formProps.errors.`${props.name}` 

is

 props.formProps.errors.id

When "name" prop equals to "amount",

props.formProps.errors.`${props.name}`

is

 props.formProps.errors.amount

But there's error. May I know how should I write it? Thank you so much!

const FormField = (props) => {
return (
......
<Field
   type="text"
   name={props.name}

   className={props.formProps.errors.`${props.name}` && props.formProps.touched.`${props.name}` ? 'is-invalid form-control' : 'form-control'}
/>
)
}

Upvotes: 1

Views: 1962

Answers (1)

Shmili Breuer
Shmili Breuer

Reputation: 4147

I think you need to do it like this

className={props.formProps.errors[props.name] && props.formProps.touched[props.name] ? 'is-invalid form-control' : 'form-control'}

Hope this helps.

Upvotes: 4

Related Questions