skip to Main Content

I would like to assign a React component to a variable. The following code works

const TextField = ({multiline, ...props}) => {

 const InputElement = (p) => multiline ? <textarea {...p} /> : <input {...p}/>

 return <InputElement {...props} />

}

but it would cause recompute on re-rendering (and lint warnings :). Of course, I can use useCallback() to avoid it, but ideally, I’d like to say something like

const TextField = ({multiline, ...props}) => {

 const InputElement = multiline ? textarea : input

 return <>{InputElement(props)}</>

}

which of course does not compile. Is there a correct syntax to do it?

2

Answers


  1. const TextField = ({multiline, ...props}) => {
    
     const inputElement = multiline ? <textarea {...props} /> : <input {...props}/>
    
     return <>{inputElement}</>
    
    }
    

    or

    const TextField = ({multiline, ...props}) => {
    
     const inputElement = p => multiline ? <textarea {...p} /> : <input {...p}/>
    
     return <>{inputElement(props)}</>
    
    }
    
    Login or Signup to reply.
  2. When you use an UpperCamelCase variable name you can use it in your JSX directly like this:

    const TextField = ({multiline, ...props}) => {
      const InputElement = multiline ? "textarea" : "input"
    
      return <InputElement {...props} />
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search