React e.preventDefault() error, onClick passing value from map - reactjs

const onSubmit = (event, val) => {
console.log(val);
event.preventDefault();
setValues({ ...values, error: "", success: "", key: val });
setDidSubmit(true);
};
Using map in React:
{data.map((e) => ( <li key={e._id}> <button
onClick={(e) => onSubmit(e, e._id)}
className="btnx btn-primary"
>
Book Now logout
</button> </li> )}
onClick I want to pass unique id e._id to the onSubmit function.
But I'm getting output as undefined.

Edit :- can you also please provide the output of e argument that you passed into the map callback ?
onClick takes a callback function and pass event as its parameter . Now , here the problem what if i want take some other parameter , to overcome this problem we have to wrap the function (can be accomplished by anonymous function or some other defined function in the code ) -> this step you did the correct but thing you did wrong is that you did not accounting the onClick callback default parameter i.e event . so you must account the event parameter in your wrapping function , then you can able to access the event object.
I hope so you get the answer.
{data.map((e) => ( <li key={e._id}> <button
onClick={(event) => onSubmit(event, e._id)}
className="btnx btn-primary"
>
Book Now logout
</button> </li> )}

Related

Why does the onClick hook get called immediately when the useMutation hook is called? [duplicate]

I pass 2 values to a child component:
List of objects to display
delete function.
I use a .map() function to display my list of objects(like in the example given in react tutorial page), but the button in that component fires the onClick function, on render(it should not fire on render time). My code looks like this:
module.exports = React.createClass({
render: function(){
var taskNodes = this.props.todoTasks.map(function(todo){
return (
<div>
{todo.task}
<button type="submit" onClick={this.props.removeTaskFunction(todo)}>Submit</button>
</div>
);
}, this);
return (
<div className="todo-task-list">
{taskNodes}
</div>
);
}
});
My question is: why does onClick function fire on render and how to make it not to?
Because you are calling that function instead of passing the function to onClick, change that line to this:
<button type="submit" onClick={() => { this.props.removeTaskFunction(todo) }}>Submit</button>
=> called Arrow Function, which was introduced in ES6, and will be supported on React 0.13.3 or upper.
Instead of calling the function, bind the value to the function:
this.props.removeTaskFunction.bind(this, todo)
MDN ref: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind
The Problem lies in how you pass your function
At the moment you are not passing the function but Calling it instead:
<Button onClick={yourFunction()} />
You can Fix this in two ways:
<Button onClick={() => yourFunction(params)} />
Or if you dont have any params:
<Button onClick={yourFunction} />
The value for your onClick attribute should be a function, not a function call.
<button type="submit" onClick={function(){removeTaskFunction(todo)}}>Submit</button>
you need to use an arrow function with onClick in order to prevent immediately invoke.
so if your button looks like this :
<button onClick={yourfunctionname()} />
it must be like this :
<button onClick={() => yourfunctionname(params)} />
JSX is used with ReactJS as it is very similar to HTML and it gives programmers feel of using HTML whereas it ultimately transpiles to a javascript file.
Writing a for-loop and specifying function as
{this.props.removeTaskFunction(todo)} will execute the functions
whenever the loop is triggered .
To stop this behaviour we need to return the function to onClick.
The fat arrow function has a hidden return statement along with the bind
property. Thus it returns the function to OnClick as Javascript can
return functions too !!!!!
Use -
onClick={() => { this.props.removeTaskFunction(todo) }}
which means-
var onClick = function() {
return this.props.removeTaskFunction(todo);
}.bind(this);
For those not using arrow functions but something simpler ... I encountered this when adding parentheses after my signOut function ...
replace this <a onClick={props.signOut()}>Log Out</a>
with this <a onClick={props.signOut}>Log Out</a> ... ! 😆
JSX will evaluate JavaScript expressions in curly braces
In this case, this.props.removeTaskFunction(todo) is invoked and the return value is assigned to onClick
What you have to provide for onClick is a function. To do this, you can wrap the value in an anonymous function.
export const samepleComponent = ({todoTasks, removeTaskFunction}) => {
const taskNodes = todoTasks.map(todo => (
<div>
{todo.task}
<button type="submit" onClick={() => removeTaskFunction(todo)}>Submit</button>
</div>
);
return (
<div className="todo-task-list">
{taskNodes}
</div>
);
}
});
I had similar issue, my code was:
function RadioInput(props) {
return (
<div className="form-check form-check-inline">
<input className="form-check-input" type="radio" name="inlineRadioOptions" id={props.id} onClick={props.onClick} value={props.label}></input>
<label className="form-check-label" htmlFor={props.id}>{props.label}</label>
</div>
);
}
class ScheduleType extends React.Component
{
renderRadioInput(id,label)
{
id = "inlineRadio"+id;
return(
<RadioInput
id = {id}
label = {label}
onClick = {this.props.onClick}
/>
);
}
Where it should be
onClick = {() => this.props.onClick()}
in RenderRadioInput
It fixed the issue for me.
It is possible to achieve this even in more readable way than:
<button onClick={() => somethingHere(param)}/>
const Comp = () => {
const [triggered, setTriggered] = useState(false);
const handleClick = (valueToSet) => () => {
setTriggered(valueToSet);
};
return (
<div>
<button onClick={handleClick(true)}>Trigger</button>
<div>{String(triggered)}</div>
</div>
);
};
That way it won't fire the state setter and won't cause too many re-renders compared to <button onClick={setTriggered(true)}/>
which is okay if you don't have any params to pass to the function.
That's because you are calling the function directly instead of passing the function to onClick
If you have passed down onClick={onClickHandler()} then, the function onClickHandler() will be executed during the time of rendering too, the () instructs to execute the function as soon as it is rendered , which is not desired here , instead we use onClick={onClickHandler} , this will execute the onClickHandler only when the specified event occurs. But if we want to pass down a argument along with the function then we can make use of ES6 arrow function.
For your Case :
<button type="submit" onClick={() => this.props.removeTaskFunction(todo)}>Submit</button>
Bit late here but here is the simple answer.
direct approach will trigger by itself due to JS DOM rendering
onClick={this.props.removeTaskFunction(todo)}
anonymous arrow function approach. it will trigger on click
onClick={()=>this.props.removeTaskFunction(todo)}
You are not passing the function as an argument you are calling it directly that why it launches on the render.
HOW TO FIX IT
there are two ways:
First
<Button onClick={() => {
this.props.removeTaskFunction(todo);
}
}>click</Button>
OR
Just bind it
this.props.removeTaskFunction.bind(this,todo);

Call component from onClick function in react js

I want to edit user details so I have
<button onClick={() => this.edit(n.id)}>Edit</button>
edit = (id) => {
<Editbranches/>
}
Here Editbranches is another component.How Can i call Component inside a user function?please Help
If you meant to render the Editbranches then:
<button onClick={() => this.setState({ edit: n.id })}>Edit</button>
{
this.state.edit && <Editbranches/>
}

How to pass parameters from a button in REACTJS?

I want to show only the paragraphs related to the selected chapter. To do this I did STATE with the selected Chapter number (the chapters are in numbers)
When I view the paragraphs in the page load it works fine.
I also want to make a list of buttons that move to the other chapters. The problem is that when I press the above buttons it does not change the STATE and I did console.log and really saw that the parameter I pass is incorrect. Where am I wrong in the code?
{allChapters.map(allChapter =>
<button key={allChapter} onClick={(allChapter) => this.handleChange(allChapter)}>
{allChapter}
</button>
)}
handleChange = (chapNum) => {
this.setState(({ currentChapter }) => ({ currentChapter: chapNum }))
console.log('chapNum', chapNum);
};
console.log()
It is important to note: {allChapter} is mirror number (1,2,3, ...) and the problem is not in it.
With your current code, the only thing you do is to rename the default onClick event parameter to allChapter. Just do this instead:
{allChapters.map(allChapter =>
<button key={allChapter} onClick={() => this.handleChange(allChapter)}>
{allChapter}
</button>
)}
Btw, you should change the variable name allChapter to chapter ;)
<button key={allChapter} onClick={(allChapter) => this.handleChange(allChapter)}>
{allChapter}
</button>
By doing this, you rename the default onClick event parameter with
allChapter
Then you pass this renamed event to the handleChange. It's why, your console.log shows an event.
The correct way to pass your parameter is :
<button key={allChapter} onClick={() => this.handleChange(allChapter)}>
{allChapter}
</button>

How to delete an item from an array (along with the 'Delete' button that next to it)? REACT

I made a list. And I want there to be a button that deletes an unwanted line from the list. The button does not work. Thanks in advance
function App() {
const [val,setval]=useState('enter please');
const [enter,setenter]=useState([]);
function handle(){
if (val!==''){setenter([...enter,val])
setval('')}
}
function delet(e){ /// here is the problem!!
//var indexi= e.target.id;
if(e>-1){ enter.splice(e,1)}
setenter(enter);
}
function handval(e){
setval(e.target.value)
}
return (
<div >
<input type="text" onChange={handval} value={val} ></input>
<button onClick={handle}> click </button>
{enter.map(index => (<li>{index} ,
<button id={index} on onClick={delet(index)}>delete</button></li> ))}
</div>
);
}
export default App;
In your onClick handler you are essentially calling delet(index), rather than passing it to be called when the event is triggered. To solve this, simply change the onClick handler to
onClick={() => delet(index)}
First of all, you need a key when using map
enter.map(index => (<li key={index}> ...
Then, in your enter array you have values typped in your input, and not an index.
So your enter.splice(e,1) is nonsense because e is not a number, but a string.
If you need the 'map' index, you should use
enter.map((value, index) => (....)

How do I make this button works

Well I have a function in a folder named auth that contain an auth.js file with this function:
logout() {
// Clear Access Token and ID Token from local storage
localStorage.removeItem('access_token')
localStorage.removeItem('id_token')
localStorage.removeItem('expires_at')
localStorage.removeItem('chatkit_user')
//TODO: callback to reset the app state.
}
Then I have a button in another folder with this code:
<button onClick={ logout() } >
Log Out
</button>
Now how can I make this work?
Just remove the ()
<button onClick={logout} >
If your function is in the same class of the render
<button onClick={this.logout} >
You must pass a function that will be called every time the button is clicked.
Instead, currently you are calling the function immediately, and then passing the result of that call.
One approach would be to wrap the attribute with an arrow function, like so:
<button onClick={() => logout()} >
Log Out
</button>
Or pass the function directly without calling it (note, this will not work properly when you pass class methods, you would need to bind them first):
<button onClick={logout} >
Log Out
</button>
If you use the onClick with the following syntax, then the logout function will be called on each render:
<button onClick={ logout() }>Log Out</button>
So my suggestion would to use just like the following if you have a functional component:
<button onClick={ () => logout() }>Log Out</button>
I hope this helps!
< button onClick={() => logout() } > Log Out < /button>
() => logout(), this basically returns you a function which will be called on click, so it should work.
if i'm understood you'r question you want to create a logout function
so
for Html part
<button onClick="logout()">logout</button>
for Javascript
function logout() {
window.localStorage.removeItem("access_token");
window.localStorage.removeItem("id_token");
window.localStorage.removeItem("access_token");
window.localStorage.removeItem("chatkit_user");
}
if i'm wrong tell me so i'll give you a another one :)

Resources