I have a parent component that makes a call to an external service onClick.
When the onClick happens, it sets the showPlaceholder component to true, which shows a placeholder whilst the external request is happening. If the request is successful the user is directed to their dashboard. If the request is unsuccessful, I want the placeholder component to not show and the parent component to render the error message.
Everything is working as expected but I can’t remove the placeholder when an error is raised. Any advice?
const ParentComponent = () => {
const [idNumber, setidNumber] = useState("");
const [showPlaceholder, setShowPlaceholder] = useState(false);
const OnClickHandler = () => {
setShowPlaceholder(true);
we post the data here and start the request
};
return (
<>
{showPlaceholder ? <showPlaceholder error={error} /> :
<>
<input
value={idNumber}
onChange={idNumber => setidNumber((idNumber))} />
<button
onClick={OnClickHandler}
>
Continue
</button>
{error && <p>errorMessage</p>}
</>
}
</>
);
};
export default ParentComponent;
Child Component
const Placeholder = (error) => {
if (error === true) {
cancelOnClickHandler();
}
const onClickHandler = () => {
STOP SHOWING THE PLACEHOLDER
};
return (
<div >
<div>
Loader...
</div>
<Link
onClick={onClickHandler}
>
cancel
</Link>
</div>
);
};
export default Placeholder;
>Solution :
There are a couple of mistakes in your code:
- All react components’ names should we written using
PascalCase:
{showPlaceholder ? <ShowPlaceholder error={error} /> // <ShowPlaceholder /> instead of <showPlaceholder />
- Below you pass
errorvariable as aproptoShowPlaceholder, but no such variable exists in your code
{showPlaceholder ? <ShowPlaceholder error={error} /> // no error varaible exists in your scope
- You are not destructuring your
propinside ofShowPlaceholdercomponent
// either v here v
const Placeholder = ({ error }) => {
if (error === true) {
... your code
// or
const Placeholder = (props) => {
// v here v
if (props.error === true) {
... your code
To remove your ShowPlaceholder when error is raised, you need to set your showPlaceholder variable to false using setShowPlaceholder when your external service returns error response, but you didn’t supply code for it so I can’t help you.
But if you want to close ShowPlaceholder with your button, do this:
// in Parent component, add this prop:
<ShowPlaceholder error={error} hidePlaceholder={() => setShowPlaceholder(false)} />
const Placeholder = (props) => {
// ... code ...
const onClickHandler = () => {
props.hidePlaceholder()
};
// ... code ...