In a previous lesson, we learned how to filter lists by language and filter down lists on the screen, but now I want to render different elements depending on whether a condition is true or not. Data is being fetched from the app component.
Because there are 13 parts to the react series, all of the code is already written here. If you're interested in how it works, you may start with part one.
If a given language is missing from the array, I want to display a message. To do this, we'll apply the condition: if a value is present in the array, display the filter component; otherwise, display the message.
We will study many conditional operators, such as the -
- If statement
- Element variables
- Logical conditional operator
- Ternary conditional operator.
The process is identical to how javascript functions.
In Lists.js, we render the details of our user list. Here, I want to reveal and hide elements depending on conditions.
Ternary Conditional operator
I will use the ternary operator as my first approach, the shorter and simple method. It contains three operands and is represented by a question mark.
condition ? true : false
This operator can be used directly in JSX by enclosing it in curly braces. If there are no items in the array list, we will return a paragraph that says "there is no detail yet!" If expected data is found in the array, we will return that transformed array element.
{(selectedCourse.length === 0) ? <p>There no detail, yet!</p> : (
selectedCourse.map((user) =>
<List key={user.id}
name={user.name}
language={user.language}
level={user.level}
/>
)
)}
Depending on the situation, either the first or second expression is executed and the component is rendered.
import List from './List'
import ListsFilter from './newUser/ListsFilter'
import { useState } from 'react'
const Lists = ({detail}) => {
const [filterCourse, setFilterCourse] = useState('JavaScript')
const filterCourseHandler = (selectedCourse) => {
setFilterCourse(selectedCourse)
console.log(selectedCourse)
}
const selectedCourse = detail.filter((user) => {
return user.language === filterCourse
})
return (
<section>
<ListsFilter selected={filterCourse} onDropdown={filterCourseHandler} />
{(selectedCourse.length === 0) ? <p>There no detail, yet!</p> : (
selectedCourse.map((user) =>
<List key={user.id}
name={user.name}
language={user.language}
level={user.level}
/>
)
)}
</section>
)
}
export default Lists
Logical && operator
The second approach is to use the AND operator, which is represented by two ampersands && and can also be used inside JSX by embedding with curly braces.
First, allow me to explain how it works. If the condition is met, it will evaluate the desired expression; if the condition is not met, it will not check further and will return false.
We'll offer Lists.js two expressions: the first one checks to see if the array has any items, in which case a message is displayed, and the second one determines whether the array length is larger than 0, in which case a list is displayed.
{(selectedCourse.length === 0) && <p>There is no detail, yet!</p>}
{(selectedCourse.length) > 0 &&
selectedCourse.map((user) =>
<List key={user.id}
name={user.name}
language={user.language}
level={user.level}
/>
)}
In the preceding example, both conditions are checked, and only the statement that is met or true is executed.
import List from './List'
import ListsFilter from './newUser/ListsFilter'
import { useState } from 'react'
const Lists = ({detail}) => {
const [filterCourse, setFilterCourse] = useState('JavaScript')
const filterCourseHandler = (selectedCourse) => {
setFilterCourse(selectedCourse)
console.log(selectedCourse)
}
const selectedCourse = detail.filter((user) => {
return user.language === filterCourse
})
return (
<section>
<ListsFilter selected={filterCourse} onDropdown={filterCourseHandler} />
{(selectedCourse.length === 0) && <p>There is no detail, yet!</p>}
{(selectedCourse.length) > 0 && (
selectedCourse.map((user) =>
<List key={user.id}
name={user.name}
language={user.language}
level={user.level}
/>
)
)}
</section>
)
}
export default Lists
Element variable
This is an alternative method for handling conditions; variables can be used to hold items and helps in conditionally rendering components. It has the advantage of being usable anywhere in the JSX, several times if necessary.
In this method, we can declare a variable in the function component called filterContainer and save the message there.
let filterContainer = <p>There is no detail, yet!</p>
then we'll use this variable in combination with an if statement to implement the conditional section and change the variable's value appropriately.
In order to determine whether we actually have the items in the array with a length greater than 0 and If the do, we'll override the value of the variable and set the map() method to it.
let filterContainer = <p>There is no detail, yet!</p>
if (selectedCourse.length > 0) {
filterContainer = selectedCourse.map((user) =>
<List key={user.id}
name={user.name}
language={user.language}
level={user.level}
/>
)
}
Then, using curly braces to enclose it, we'll add that variable as an expression in JSX. It can dynamically return an array or a message.
import List from './List'
import ListsFilter from './newUser/ListsFilter'
import { useState } from 'react'
const Lists = ({detail}) => {
const [filterCourse, setFilterCourse] = useState('JavaScript')
const filterCourseHandler = (selectedCourse) => {
setFilterCourse(selectedCourse)
console.log(selectedCourse)
}
const selectedCourse = detail.filter((user) => {
return user.language === filterCourse
})
let filterContainer = <p>There is no detail, yet!</p>
if (selectedCourse.length > 0) {
filterContainer = selectedCourse.map((user) =>
<List key={user.id}
name={user.name}
language={user.language}
level={user.level}
/>
)
}
return (
<section>
<ListsFilter selected={filterCourse} onDropdown={filterCourseHandler} />
{filterContainer}
</section>
)
}
export default Lists
If Statement
Now, we will use an if return statement to trigger code based on a condition. This is the simplest way to deal with the condition.
In
vanilla javascript executes an if statement and executes a block of code if the condition returns true, While React renders a separate component or JSX element entirely according to the supplied condition.
Also, keep in mind that using an if condition inside JSX, will not work.
In the following example, I'll use if and compare array length to 0 to see if there are any items in the array, and if so, I'll return a JSX element span. If the condition returns false, I'll return a different JSX code and it'll output lists, no need to use else.
if (props.items.length === 0 ) {
return There is no detail, yet!
}
return (
<section>
{props.items.map((user) =>
<List key={user.id}
name={user.name}
language={user.language}
level={user.level}
/>
)}
</section>
)
Extract logic in new component
Because only a little section of the JSX that we returned changed, I must extract the filter logic into a new component in order for it to function in my application. There, I will run the condition and re-render the component.
Create a UserFilter.js file in the component folder and then move the map() loop output, which yields a list item, to the file's return statement. Of course, the selectedCourse method no longer exists in the UserFilter component so we'll pass the function through props.
import List from "./List"
const UserLists = (props) => {
if (props.items.length === 0 ) {
return <span>There is no detail, yet!</span>
}
return (
<section>
{props.items.map((user) =>
<List key={user.id}
name={user.name}
language={user.language}
level={user.level}
/>
)}
</section>
)
}
export default UserLists
Go ahead and import the UserFilter component into the List component at this point along with adding this element in JSX. Now, define the items property on the UserFilter element to replace selectedCourse with props.listItems inside the UserFilter component.
import ListsFilter from './newUser/ListsFilter'
import { useState } from 'react'
import UserLists from './UserLists'
const Lists = ({detail}) => {
const [filterCourse, setFilterCourse] = useState('JavaScript')
const filterCourseHandler = (selectedCourse) => {
setFilterCourse(selectedCourse)
console.log(selectedCourse)
}
const selectedCourse = detail.filter((user) => {
return user.language === filterCourse
})
return (
<section>
<ListsFilter selected={filterCourse} onDropdown={filterCourseHandler} />
<UserLists items={selectedCourse} />
</section>
)
}
export default Lists
Conclusion
In this section, we learned how to use condition in React using four different methods and thoroughly examined each of our four options - element variables, the if statement, the ternary operator, and the short circuit (&&) operator. If there is no item return in the array, we render message; however, when there are arrays in the list, we render component.
0 Comments:
Post a Comment