0

I'm new to React, but not to programming. In the following code, desc never changes state, and I believe this is because the tag isn't entirely compatible with the value and onChange attribute/event handler im trying to use with it.

What im trying to do is get the text information from the span tag when you press the className='submit' button. I saw some videos where people suggested the method i have in place now, where you constantly update the state onChange, however this seems janky to me and if theres a better way where you get the text only onClick once instead of constantly updating, please let me know.

Also, I'm using a span with the contentEditable attribute because of CSS styling reasons, I want a borderless box that expands itself and the container its in instead of the text going off the page to the right. I attached a screenshot of what I mean.

ScreenshotOfCard

    const [title, setTitle] = useState('');
    const [desc, setDesc] = useState('');

        return (
            <div className='card-container'>
                <div className='card'>
                    <h1 className='card-title'>
                        <input className='titletext' value={title} onChange={e => setTitle(e.currentTarget.value)} placeholder='Who do you need?'></input>
                    </h1>
                    <p className='card-desc'>
                        <span className='textarea' value={desc} onChange={e => setDesc(e.currentTarget.value)} contentEditable></span>
                    </p>

                    <button className='submit' onClick={event => {
                        /*
                            Add job to the database (async)

                            Add new card with information submitted in the list right below
                        */
                        event.preventDefault();
                        console.log(title);
                        console.log(desc);
                        
                    }}></button>
                </div>
            </div>
        );
}

1 Answers1

1

so I figured out what the problem was. onChange doesn't work with span tags, even in vanilla JS. The solution was to change onChange to onInput, and use e.currentTarget.innerText

Thanks to Suhag Lapani88 for narrowing it down though he offered what I thought was going to be a solution with useRef, because I thought I was using useRef wrong.