如何在 React 中使用可选 href 渲染 <a>
介绍
当您开发一款满足所有类型最终用户需求的应用时,条件渲染可让您自动化代码以处理所有预定义和动态情况,而无需硬编码解决方案。除了保持代码简洁、简短和可读之外,它还通过一些简单的结构逻辑管理大量可能性。
在本指南中,您将学习如何根据特定条件在 React 应用中使用可选href呈现锚元素。
标签概述
HTML 中的锚标记用于使用 href 属性导航到不同的网页。此 href 属性包含目标页面的 URL 或路径。它可以是相对 URL 或绝对 URL。在 React 中,相对 URL 应始终由 React Router 提供的链接标记处理,纯锚标记仅应用于绝对路径。您还可以将相对 URL 视为应用内导航,例如导航到应用程序的特定路由,将绝对路径视为外部链接。渲染可选href背后的主流逻辑也可以方便地扩展到<link>,事实上,任何其他 JSX 元素或组件。
可选渲染:用例和解决方案
考虑一个简单的用例,您正在维护一个包含所有通过您的应用申请过职位的人员的数据库。在前端,您可以以以下格式获取要输出的数据。
user={
name: '',
email:'',
sector:'',
linkedinHandle:'',
...
}
Your form asked users to enter their LinkedIn handles, but it wasn't a mandatory field, so there's a strong possibility that some people left it blank. While outputting the data, you do something like this:
<a href={user.linkedninHandle}></a>
If the backend returned an empty string, your href would be rendered as an empty string too, but that's not an optimal solution. If linkedinHandle doesn't exist for a user, the <a> shouldn't be visible at all, but the empty link is still clickable even though it points nowhere. Additionally, this could throw errors in cases when the property is returned as null or undefined. The accurate solution is using conditional rendering on the <a> itself so either it is rendered along with the appropriate link or the other JSX element is rendered.
Creating a New Project
Make sure you have Nodejs and npm installed in your machine (at least version 8 or higher) along with a code editor and a web browser (preferably Chrome or Firefox).
Create a new project using create-react-application:
npx create-react-app optional-href-rendering
Cleaning up the Template
Ideally, you could have a separate component handling this kind of logic in your app, but for brevity, let's put all the code inside App.js. Remove the logo, App.css, and all their imports from App.js. Clean out the starter template inside the App component. Your App.js should look like this:
import React from 'react';
function App() {
return (
<div className="App">
</div>
);
}
export default App;
Setting State for Toggling Condition
The condition is usually based on the type of data you receive from the backend, but a good practice is to use a toggling state to understand the rendering more dynamically. Consider data received from the backend, and based on that, a toggling state is set to either true or false. If it's true, the href will be rendered, and if false, it will not be rendered.
import React,{useState} from 'react';
function App() {
const [state,setState]=useState(false);
let url="";
return (
<div className="App">
<a href={url}>LinkedIn handle</a>
</div>
);
}
export default App;
This renders a simple <a> with an empty href, but it's still a clickable link. Let's add conditional rendering to it.
Optionally Rendering an Element
If the href attribute for the user exists, the state is set to true and the <a> tag is shown, otherwise a message is displayed. Wrap the message to be shown in a JSX element and assign that element to a variable that can be conditionally outputted.
let element=<p>No handle exists for this user!</p>;
Using an If Statement
Before rendering anything, simply check if the state is true and assign <a> to that element, otherwise let the whole component render as it is.
import React,{useState} from 'react';
function App() {
const [state,setState]=useState(false);
let url="";
let element=<p>No handle exists for this user!</p>;
if(state) element=<a href={url}>LinkedIn handle</a>;
return(
<div className="App">
{element}
</div>
);
}
export default App;
Since the state is initially false, the message is displayed. Setting it to true will render the link as it is.
...
const [state,setState]=useState(true);
...
Using the Ternary Operator
The same check can be performed using a ternary operator to keep the code more readable.
...
let element= state? <a href={url}>LinkedIn handle</a>
: <p>No handle exists for this user!</p>;
...
Using the && Operator
In case you don't want to display an element at all for the false state value, the && operator can be conveniently used.
import React,{useState} from 'react';
function App() {
const [state,setState]=useState(false);
let url="";
let element=<a href={url}>LinkedIn handle</a>;
return(
<div className="App">
{state && element}
</div>
);
}
export default App;
Since the state is evaluated first, the element is not rendered since it's false. Changing it to true renders the empty parent div.
Meeting the Needs of Your App
When implementing your solution to meet the need of your app, remember that toggling the state using setState should be done in a function performing the relevant check with the data received from the backend. The initial value of the state is arbitrarily chosen here, but you should initialize the state to a legal value depending on your code. If the evaluation of the condition is more dynamic in nature or it is not known beforehand, use relevant lifecycle hooks to ensure your code remains intact. Finally, it is not mandatory to use a state variable for evaluating your condition. In some cases, even a simple JavaScript variable will do, provided its scope is well defined and doesn't crash your code anywhere.
Conclusion
Optionally rendering an attribute is never an optimal solution to conditionally display content on your app. The emphasis should always be more on the element itself, as attributes do not affect its physical appearance entirely. Also, when conditionally rendering an element or even a component, all scenarios should be well thought through. Avoid rendering empty tags, elements, or strings and focus on giving feedback to the user by rendering something else in their place.
If you have any queries, feel free to reach out at Codealphabet.
了解更多
查看这些 React 课程以继续学习!
免责声明:本内容来源于第三方作者授权、网友推荐或互联网整理,旨在为广大用户提供学习与参考之用。所有文本和图片版权归原创网站或作者本人所有,其观点并不代表本站立场。如有任何版权侵犯或转载不当之情况,请与我们取得联系,我们将尽快进行相关处理与修改。感谢您的理解与支持!
请先 登录后发表评论 ~