I am trying to set a attributes based on certain condition. attributes do certain action with there name
<Button
onClick={() =>
updateSegmentDetailsHandler(data.title, data.description)
}
isLoadingIndicator={btnLoading}
disabled={!data.title || !data.description || btnLoading}
btnColor={'primary'}
data-bs-dismiss='modal' // how to set this attributes based on condition
className="btn text-white"
>
Save changes
</Button>
<Button
onClick={() =>
updateSegmentDetailsHandler(data.title, data.description)
}
isLoadingIndicator={btnLoading}
disabled={!data.title || !data.description || btnLoading}
btnColor={'primary'}
{btnLoading && ...[data-bs-dismiss='modal']}
className="btn text-white"
>
Save changes
</Button>
I did something like this but it didn’t work
3
Answers
you can add the condition like js only
data-bs-dismiss={btnLoading ? "modal" : null}
If the
btnLoading
is true thendata-bs-dismiss
attribute will getmodal
value otherwise it will have null as valueMaybe change your code like this solve your problem.
You’re very close with the idea of
spread
ing the the prop into the Componentinstead of:
try:
This will optionally create the object which will then be
spread
in. When the condition is not met, React will findundefined
and the prop will not be addedI believe for custom attributes like
data-bs-dismiss
(rather than something standard likeclass
is, which in React isclassName
) the attribute should be written "as is" instead of with camalCase (e.g.style={{ paddingTop: "10px" }}
);but I must admit I’ve not tried to use non-standard attributes attributes…EDIT:
I tested this for both my custom
Button
component and the rawbutton
element and both worked fine…This implies a deeper problem with either
title
ordescription
being empty strings or the value ofbtnLoading
never beingfalse
. I’d recommend someconsole.log
s and uses oftypeof
…e.g.
console.log("btnLoading", btnLoading, typeof btnLoading);
On a second look, it also occurred to me that the line should be:
meaning that when the button is not loading, the custom prop should be added.