Home > other >  React set multiple defaultValue to test input
React set multiple defaultValue to test input

Time:12-07

I want a default value for each different input component but it only works with one default value.

Page:

<InputField nameValue={'name'} />
<InputField productValue={'product 6sd4f'} />
<InputField informationValue={'information 123'} />

Input component:

function InputField({nameValue, productValue, informationValue}) {
 return (
     <div className='inputDiv'>
        <input type="text" placeholder='type info' defaultValue={`${nameValue ? nameValue : ''} ${productValue ? productValue : ''} ${informationValue ? informationValue : ''}`} />
     </div>
 )
}

CodePudding user response:

I'm not sure if you really want to combine all of them together if they're all provided. Instead, you can first determine a defaultValue inside the component, and then use that value for the default value of the input:

<div id="root"></div><script src="https://unpkg.com/[email protected]/umd/react.development.js"></script><script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script><script src="https://unpkg.com/@babel/[email protected]/babel.min.js"></script>
<script type="text/babel" data-type="module" data-presets="react">

function InputField ({nameValue, productValue, informationValue}) {
  /**
   * If all of the values are provided, they will all be combined in the string
   * but I don't think this is what you want
   */
  // const defaultValue = `${nameValue ? nameValue : ''} ${productValue ? productValue : ''} ${informationValue ? informationValue : ''}`;

  /** Instead, set it to the first one that has a truthy value, in order: */
  const defaultValue = nameValue ? nameValue
    : productValue ? productValue
    : informationValue ? informationValue
    : '';
  
  return (
    <div className='inputDiv'>
      <input
        type="text"
        placeholder="type info"
        defaultValue={defaultValue}
      />
    </div>
  );
}

function Example () {
  return (
    <div>
      <InputField nameValue="name" />
      <InputField productValue="product 6sd4f" />
      <InputField informationValue="information 123" />
      <InputField nameValue="first" productValue="second" informationValue="third" />
      <InputField productValue="second" informationValue="third" />
      <InputField nameValue="" productValue="second" informationValue="third" />
      <InputField nameValue="" productValue="" informationValue="third" />
    </div>
  );
}

ReactDOM.render(<Example />, document.getElementById('root'));

</script>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

enter image description here

it works correctly! can you attach your issue?

  • Related