Home > Software engineering >  Warning: Invalid value for prop `value` on <input> tag
Warning: Invalid value for prop `value` on <input> tag

Time:12-12

I'm getting this warning and I can't find out why: "Invalid value for prop value on tag. Either remove it from the element, or pass a string or number value to keep it in the DOM."

const [inputValues, setInputValues] = useState({});
const sendPost = async () => {
    if (inputValues.link.length > 0) {
      setPostList([...postList, inputValues]);
      setInputValues('');
    } else {
      console.log('Empty inputs. Try again.');
    }
  };

  const onInputChange = (event) => {
    const name = event.target.name;
    const value = event.target.value;
    setInputValues(values => ({...values, [name]: value}))
  };

const renderConnectedContainer = () => (
    <div className="connected-container">
      <form
      onSubmit={(event) => {
        event.preventDefault();
        sendPost();
      }}
    >
      <input 
        type="text" 
        placeholder="Enter title!" 
        name="title" value={inputValues.title || ""} 
        onChange={onInputChange}/>
      <input 
        type="text" 
        placeholder="Enter link!" 
        name="link" 
        value={inputValues.link || ""} 
        onChange={onInputChange}/>
      <textarea 
        type="text-area" 
        placeholder="Enter description!" 
        name="description" 
        value={inputValues.description || ""} 
        onChange={onInputChange}/>
      <button type="submit" className="cta-button submit-post-button">Submit</button>
    </form>
   </div>
  );

CodePudding user response:

In the sendPost handler, you are resetting the inputValues state to an empty string '' instead of back to the initial state of an empty object {}. inputValues.title is ok since it's just undefined, but inputValues.link (i.e. ''.link) is actually a deprecated function.

String.prototype.link

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The link() method creates a string representing the code for an <a> HTML element to be used as a hypertext link to another URL.

Just reset the inputValues back to the initial state.

const sendPost = async () => {
  if (inputValues.link.length > 0) {
    setPostList([...postList, inputValues]);
    setInputValues({});
  } else {
    console.log('Empty inputs. Try again.');
  }
};
  • Related