Reputation: 23
I am trying to run a function by clicking Modify2 or Edit2 in the code. It runs all the time the function defined with onClick and then showCard again
It should just trigger showConn !
And why is it running showCard right after showConn?
Thanks for any suggestions.
The Code:
import React, { useState, useEffect } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import './App.css';
function App() {
const [list, setList] = useState(true);
const [card, setCard] = useState(false);
const [netconn, setNetconn] = useState(false);
const [networks, setNetworks] = useState([]);
const [network, setNetwork] = useState({});
useEffect(() => {
fetch(window.location.protocol+"//"+window.location.hostname+":3001/networks/list")
.then((response) => response.json())
.then((responseJson) => {
setNetworks(responseJson.data);
});
}, []);
let showCard = (id) => {
console.log( "Show Card");
fetch(window.location.protocol+`//`+window.location.hostname+`:3001/networks/${id}`)
.then((response) => response.json())
.then((responseJson) => {
setNetwork(responseJson.data);
setList(false);
setNetconn(false);
setCard(true);
});
};
let showConn = (id) => {
console.log( "Show Connection");
setList(false);
setCard(false);
setNetconn(true);
};
let showList = () => {
setCard(false);
setNetconn(false);
setList(true);
};
const handleSubmit = (event) => {
event.preventDefault();
}
const handleGetconn = (event,id) => {
event.preventDefault();
alert(id);
showConn(id)
}
return (
<div className="container">
{netconn ? (
<div className="row">
<div className="col-auto">
<div
onClick={() => showCard(network._id)}
className="btn btn-primary">Submit</div>
<div
onClick={() => showList()}
className="btn btn-default">Cancel</div>
</div>
</div>
) : null}
{list ? (
<div className="list-group">
{networks.map((network) => (
<li
key={network._id}
onClick={() => showCard(network._id)}
className="list-group-item list-group-item-action">
{network.name}
</li>
))}
</div>
) : null}
{card ? (
<div className="row">
<div className="col-auto">
<div
onClick={(e) => handleGetconn(e,network._id)}
className="btn btn-success">
Modify2
</div>
<div onClick={() => showConn(network._id)} className="btn btn-primary">
Edit2
</div>
<div onClick={() => showList()} className="btn btn-default">
Back
</div>
</div>
</div>
) : null}
</div>
);
}
export default App;
UPDATE the code and added () => to onclick tags where it was missing
Upvotes: 0
Views: 56
Reputation: 41
You are calling the function showCard
on every render here:
onClick={showCard(network._id)}
In the code excerpt above, the onClick prop value is the return value of the function call which is called on every render.
The <li>
element has the onClick
prop set correctly.
onClick={() => showCard(network._id)}
Here, the onClick prop value is a reference to a function which is called on click event.
Upvotes: 1