Reputation: 1235
I have a react component that displays an address with a copy to clipboard icon next to it.
The address is returned with 5 elements: address1, address2, city, state, and zip
When I display the elements on the front end, I'm able to conditionally render them based on if they exist. However I'm not sure how to pass that to my CopyButton.
I started to write a formatter but I'm running into issues when it comes down to passing the formatted address in.
Here's my current code for the formatter as well as the displayed string and CopyButton component for reference:
Formatter
const formatAddress = (addressLine1: string, addressLine2: string, city: string, state: string, zip5: string ) => {
let formattedAddress = ''
address2 ? formattedAddress = `${addressLine1} ${addressLine2}, ${city}, ${state} ${zip5}` : formattedAddress = `${addressLine1}, ${city}, ${state} ${zip5}`
return formattedAddress
}
<p> element with address and CopyButton
{address1
? (
<p data-testid="address">
{address1}
{address2 && `, ${address2}`}
{city && `, ${city}`}
{state && `, ${state}`}
{zip && ` ${zip.substring(0, 5)}`}
{formatAddress(address1, address2, city, state, zip)}
<ButtonCopyText
a11yText="Copy Address"
textToCopy={formattedAddress}
/>
</p>
) : (
<p data-testid="no-address">--</p>
)
}
Upvotes: 0
Views: 1931
Reputation: 826
let formattedAddress = ''
address2 ? formattedAddress = `${addressLine1} ${addressLine2}, ${city}, ${state} ${zip5}` : formattedAddress = `${addressLine1}, ${city}, ${state} ${zip5}`
could be this
const formattedAddress =
`${addressLine1}${addressLine2 ? ` ${addressLine2}` : ''}, ${city}, ${state} ${zip5}`.trim();
Also, you never define formattedAddress
when you go to use it as a prop passed to your <ButtonCopyText />
component. You could call the function right there in the prop assignment, or assign the return value of the function into that variable somewhere outside of the JSX.
Upvotes: 1