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);
How come the following React Button Emitter is not working? It should display the word Apple, with button click.
function App() {
return (
<div>
<button onClick={handleClick('apple')}>
Test Button
</button>
</div>
)
}
function handleClick(props) {
console.log(props)
}
In order for it to get called on click you need to pass a function. Right now your code is invoking the function:
function App() {
return (
<div>
{/* Creates an anonymous function that calls `handleClick` */}
<button onClick={() => { handleClick('apple'); }}>
Test Button
</button>
</div>
)
}
By doing onClick={handleClick('apple')} what you are doint is to put the result of handleClick('apple') at rendering time, not onClick time.
onClick={() => handleClick('apple')} will work because you are creating a function and assign it to onClick, without executing it yet.
This is how React works, because what you are writing is actually just javascript (not html, even if it looks like so).
Your way would instead be perfectly ok if you were using Vue, for example, because in that case you are working in an html template (unless you don't want to use jsx..)
in react I am displaying products I.E.
{renderPosts.map((item, index) => (
...
now, in each product, there is a button to delete that product, inside a button I have onclick that calls sweetAlert to delete particular product:
<Button
color="danger"
simple
justIcon
onClick={warningWithConfirmMessage}
>
Everything works fine like that... but if I want to pass ID of the product that has to be deleted...
<Button
color="danger"
simple
justIcon
onClick={warningWithConfirmMessage(item.postId)}
>
Now I am having error:
Too many re-renders. React limits the number of renders to prevent an infinite loop.
How I can pass anything to function... anybody
Thanks in advance!
The new onClick handler you're passing is calling the warningWithConfirmMessage every time it renders. To pass the function as a handler function instead of calling it, use:
onClick={() => warningWithConfirmMessage(item.postId)}
This question already has answers here:
React onClick function fires on render
(13 answers)
Closed 3 years ago.
I am building a website that allows a user to create a job opening, assign to it different requirements and delete it.
I have two main components:
HRdashboard is the parent component in which all the job openings are listed.
MyOpeningCard is the card that contains information of a single job opening. It comes from the .map function in the parent component:
HRdashboard
function HRdashboard({changeAuthLoginHR}) {
const [HRuser, setHRuser] = React.useState([]);
const [openings, setOpenings] = React.useState([]);
useEffect( ()=> {
let unmountedOpenings = false
async function getAllOpenings(){
let response = await axios("http://www.localhost:3000/api/v1/openings");
if(!unmountedOpenings)
setOpenings(response.data)
}
let jwt = window.localStorage.getItem('jwt')
let result = jwtDecode(jwt)
setHRuser(result)
changeAuthLoginHR()
getAllOpenings()
return () => {
unmountedOpenings = true
}
}, [],
)
return(
<div>
<Container style={{marginTop: "50px"}}>
<Row>
{openings.map(opening =>
<Col>
<MyOpeningCard key={opening.id} opening={opening} /> # Here is where the child is
</Col>
)}
</Row>
</Container>
</div>
)
}
MyOpeningCard
function MyOpeningCard({opening}) {
return(
<div>
<Card style={{ width: '18rem', marginTop: "15px"}}>
<Card.Body>
<Card.Title>{opening.title}</Card.Title>
<Card.Subtitle className="mb-2 text-muted">Requirements: </Card.Subtitle>
<Card.Text>
{opening.requirements[0].requirements.map(requirement => <li>{requirement}</li>)}
</Card.Text>
<div>
<Card.Link href="#" onClick={console.log(opening.id)}>Click Here</Card.Link> # If I click here, it console.log all the IDs, not only this opening id.
</div>
</Card.Body>
</Card>
</div>
)
}
My question:
If I click on Click Here in my child component, it triggers console.log(opening.id).
I was expecting to see in console only the opening.id of the Job Opening I click. However, I see all the ids of the openings.
Why is it so?
Because your onClick prop is calling a function which immediately runs the same time your child component is rendered, without even clicking, for all the child components.
onClick={console.log(opening.id)}
So, when you use the .map() method, all of your <MyOpeningCard /> components get rendered, each of them immediately calling console.log() again and again, hence you see all the ids logged in the console.
You should pass a callback, instead, to the onClick prop which will be executed only when a click happens.
Change it to
onClick={() => { console.log(opening.id) }}
Parentheses after a function name executes the function.
even-though you didn't mean to do that, that's why wrapping it with an additional Arrow Function is needed, it happens as:
() => console.log('something'), this Arrow Function is not going to be invoked until the click actually occurs.
while if you pass console.log this way -no parenthesses-, it'll be logging the whole Event only upon the Click event occurrence.
https://gist.github.com/justgoof9/7610432925d5f921dc745071d1d67657
So I made the onDismiss button but when I pass it on to the onClick in the Delete button it doesn't do anything. Can anyone help me?
<IconButton aria-label="Delete" onClick={() => this.onDismiss() }>
You are creating an anonymous function that returns a onDismiss function, so when onClick is called due to a click, its only returning the function, not calling it. BTW, creating anonymous functions inside renders is frowned upon consider refactoring it out to its own function