@rollin
Conditional rendering in React can be implemented using various techniques. Here are a few examples:
- Using if-else statements:
1
2
3
4
5
6
7
|
render() {
if (condition) {
return <Component1 />;
} else {
return <Component2 />;
}
}
|
- Using the ternary operator:
1
2
3
4
5
6
7
|
render() {
return (
<div>
{condition ? <Component1 /> : <Component2 />}
</div>
);
}
|
- Using logical && operator:
1
2
3
4
5
6
7
|
render() {
return (
<div>
{condition && <Component1 />}
</div>
);
}
|
- Using a separate function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
renderComponent() {
if (condition) {
return <Component1 />;
} else {
return <Component2 />;
}
}
render() {
return (
<div>
{this.renderComponent()}
</div>
);
}
|
It's important to note that the condition
in all these examples can be any JavaScript expression that evaluates to a boolean value.