Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

reactjs - Conditional styling based on whenever there is a certain field value added by cms in React/Typescript app

In my React/Typescript component I render a <Link /> component whenever the value (data.link?.text and data?.link?.url) is added by the CMS.

{data.link?.text && data?.link?.url && (
 <Link to={data?.link?.url}>
)}

I use Typescript Optional Chaining to conditionally render the Link or not. So if the text and url of the link field are filled it renders the <Link /> component.

The Link type:

export type Link = {
 link: {
   url: string;
   text: string;
 };
}

If the Link component doesn't exist on the page/isn't rendered I want to add some styling (margin-bottom) to the List component.

The structure of the component looks like this:

<List>
 <div css={styles.list}>
  // Mapped list items here
 </div>
</List>

{data.link?.text && data?.link?.url && (
 <Link css={styles.link} to={data?.link?.url}>
  {data.link.text}
 </Link>
)}

So somehow I have to create a boolean and based on that boolean, in my MyComponent.styles.ts I can do something like:

margin-bottom: ${haslink ? `0` : `35px`}; 
question from:https://stackoverflow.com/questions/65868865/conditional-styling-based-on-whenever-there-is-a-certain-field-value-added-by-cm

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you could create a div with the extra margin bottom that you can conditionally render based on the link url.

<List>
  <div css={styles.list}>
    // Mapped list items here
  </div>
</List>

{data.link?.text && data?.link?.url ? (
  <Link css={styles.link} to={data.link.url}>
    {data.link.text}
  </Link>
) : (
  <div style={{ marginBottom: '35px' }} /> // <-- adjust how you style this element as needed
)}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...