Search code examples
javascriptreactjsparameterssyntaxonchange

How can I pass arguments in this line of code in ReactJS functional Component?


I am creating elements using react.createElement, which works fine, and I'm trying to add the onchange attribute and a function to it. Looks like this:

React.createElement('input', {type : 'text', id : 'titleInput', className : 'eventInput', onChange : SetTitle})

For functions without parameters it's easy, you can just put the function like:

React.createElement('button', {type : 'submit', id : 'submitNewEventButton', className : 'eventInput', onClick : SubmitNewEvent}, 'Submit')

The submit function doesn't take parameters but the SetTitle function in the first line of code wants to get the value of it's own element. In reacts return html method you can just put something like:

<input type='text' id='emailInput' className='inputField' onChange={e => SetEmail(e.target.value)}/>

So it get the right value, how can I do this in the createElement situation?

UPDATE

I am using a functional component with states like:

const [title, SetTitle] = useState('');

When creating the element with:

React.createElement('input', {type : 'text', id : 'titleInput', className : 'eventInput', onChange : (e) => SetTitle(e.target.value)})

or:

React.createElement('input', {type : 'text', id : 'titleInput', className : 'eventInput', onChange(e){SetTitle(e.target.value)}})

The set state function SetTitle() is not running to my knowledge, when submitting, I use the state variable title, and submit to a database, but title is always empty, from it's initial state. When I have this element in my return like:

return(
    <input type='text' id='titleInput' className='inputField' onChange={e => SetTitle(e.target.value)}/>
);

and you type in the input, the state is updating properly, why is the React.createElement way not satisfying this task?


Solution

  • You can follow the same as in case with html. Just replace the

    React.createElement('input', {type : 'text', id : 'titleInput', className : 'eventInput', onChange : SetTitle }
    

    With

    React.createElement('input', {type : 'text', id : 'titleInput', className : 'eventInput', onChange : (e) => SetTitle(e.target.value) }