skip to Main Content

I’m just trying to build a frontend builder React app. Everything goes as expected but not one.

const [displayContent, setDisplayContent] = useState(
        props.contentInside.html
    );
<button
                        onClick={() => {
                            props.changeLanguage("HTML");
                            setDisplayContent(props.contentInside.html);
                        }}
                    >
                        HTML
                    </button>
                    <button
                        onClick={() => {
                            props.changeLanguage("CSS");
                            setDisplayContent(props.contentInside.css);
                        }}
                    >
                        CSS
                    </button>
                    <button
                        onClick={() => {
                            props.changeLanguage("Js");
                            setDisplayContent(props.contentInside.js);
                        }}
                    >
                        Js
                    </button>
<textarea
                    className="bg-[rgb(20,20,20)] p-2 pt-1 border-[1px] border-t-0 border-yellow-300 border-dashed text-yellow-300"
                    placeholder={placeHolder}
                    defaultValue={displayContent}
                    onChange={props.updateContent}
                ></textarea>

See it should work perfect but not yet and idk y.
check these pictures
enter image description here
enter image description here

As you can see in this pic, the content is updated on the element inspection, but not in the actual DOM.

2

Answers


  1. It looks like the defaultValue prop in the textarea is causing the issue. The defaultValue prop is only used to set the initial value of the textarea and doesn’t update the value of the textarea when the state changes.

    You can fix this issue by using the value prop instead of defaultValue. Here’s the updated code:

    <textarea
      className="bg-[rgb(20,20,20)] p-2 pt-1 border-[1px] border-t-0 border-yellow-300 border-dashed text-yellow-300"
      placeholder={placeHolder}
      value={displayContent}
      onChange={props.updateContent}
    >
    </textarea>
    

    By using value instead of defaultValue, the textarea will be updated with the new value whenever displayContent changes.

    Login or Signup to reply.
  2. As mentioned in supun answer you have to use value not defaultValue to display the value of displayContent in the textarea, and the reason why you cannot update it is because each time you type in the textare it is props.updateContent that is executed so displayContent is the same, therefore, the onChange handler should update displayContent:

    value={displayContent}
    onChange={(e) => {setDisplayContent(e.target.value)}}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search