In React, conditional rendering refers to showing or hiding elements based on certain conditions. There are several ways to conditionally render components in React:
render() {
if (condition) {
return <Component1 />;
} else {
return <Component2 />;
}
}
render() {
return (
{condition ? <Component1 /> : <Component2 />}
);
}
render() {
return (
{condition && <Component />}
);
}
render() {
return (
<div>
{array.map(item => (
{item.condition && <Component key={item.id} />}
))}
</div>
);
}
constructor(props) {
super(props);
this.state = {
showComponent: true
};
}
toggleComponent = () => {
this.setState({ showComponent: !this.state.showComponent });
}
render() {
return (
<div>
<button onClick={this.toggleComponent}>Toggle Component</button>
{this.state.showComponent && <Component />}
</div>
);
}
By using these methods, you can conditionally render components in React based on various conditions.