I have this React component:
import * as React from 'react';
import './Pless.css';
interface Props {
handleClose: () => void;
showPless: boolean;
}
export class Pless extends React.Component<Props> {
constructor(props: Props) {
super(props);
}
render() {
const { showPless } = this.props;
const showHideClassName = showPless ? 'show-div' : 'display-none';
console.log(this.props);
return (
<div className={showHideClassName}>
<div id="mypless" className="pless">
<div className="pless-content">
<div className="pless-header">
<span className="close" onClick={this.props.handleClose}><u>Close</u> X</span>
<h2 />
</div>
<div className="pless-body">
<h2 className="content-header">Header</h2>
<p className="main-text">Text:</p>
<ol className="main-text">
<li>List item</li>
</ol>
</div><div className="pless-footer">
<label htmlFor="isPless">
<input id="isPless" name="isPless" type="checkbox" /> Relevant text
</label>
</div>
</div>
</div>
</div>
);
}
}
When this popup appears I want to call a rest endpoint if the checkbox is ticked and close is clicked. If the checkbox is not ticked and close is pressed, no call is made. I have the checkbox displaying and it can be ticked/unticked but I don't know how to call the endpoint based on it being selected. How is this done?
First you need a state for your checkbox input. Something like:
const [boxState, setBoxState] = useState(false);
then you need to add a change event on the checkbox input:
onChange={toggleHandler}
The handler will be something like:
const toggleHandler = () => setBoxState(prevState => !prevState);
At this point in your click event for closing, you can reference the checkbox state. In your case you should have something like:
onClick={this.props.handleClose.bind(null, boxState)};
Now wherever the function handleClose is defined, you should modify it to accept this boxState argument which will be a boolean saying whether the checkbox was checked or not. Use this argument in an if statement to achieve what you want.
I wrote the following example hoping it helps:
import { useState } from 'react';
export function CheckBoxxx() {
const [boxState, setBoxState] = useState(false);
const toggleHandler = () => setBoxState(prevState => !prevState);
const closeHandler = () => console.log(boxState ? 'Do something' : 'Do not');
return (
<>
<button onClick={closeHandler}>Close</button>
<label>
Check me
<input
name="isGoing"
type="checkbox"
onChange={toggleHandler}
/>
</label>
</>
);
}