I have an App.js which calls a function DisplayQuestions in its render method. What is the right place to declare the handleClick() function? I tried to declare it inside of DisplayQuestions but that never seems to get called. I looked at this similar issue but couldnt get the binding working like this question, possibly because the DisplayQuestions component is a function (not part of App.js).
The button displays fine, but clicks are never logged to console. I have tried creating the button using the event property and the onclick property with the same result:
class App extends React.Component {
render() {
return (
<div className="App"></div>
<DisplayQuestions />
)
}
DisplayQuestions:
export function DisplayQuestions() {
const [notes, setNotes] = useState([{ questions: [], definition: "" }]);
const [query, setNotesQuery] = useState("Dynamo");
const [isLoading, setIsLoading] = useState(true);
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
//handleClick function
var handleClick = (q) => {
console.log(`handleClick`, q)
}
useEffect(() => {
const fetchData = async () => {
setIsLoading(true);
setNotes(await NotesApiQuery(query))
setIsLoading(false);
};
fetchData();
}, [query]);
return (
<div>
{isLoading ? (
<div> Loading ...</div>
) :
<div>
<h3>Notes({notes.length}):</h3>
{
notes.map((n) => (
<div>
<li>
<span style={{ visibility: 'hidden' }} id={n.questions}>{n.definition}</span>
<button event={handleClick(n.questions)}>Show/Hide ans</button>
</li>
</div>
)
)
}
</div>
}
</div>
);
}
Appcode won't compile. JSX doesn't allow multiple top-level elements.thiswork in the callback" That's for class components, not functional components using hooks.<button onClick={activateLasers}> Activate Lasers </button>