I am using switch statement inside a react file .Getting Expression Expected error in first case line.
export default ({handle, state}) => (
<div style={styles.container} >
<h3 style={{margin: 0, marginBottom: 15}}>InputData</h3>
{items.map((item) => (
<div style={styles.lineContainer}>
switch(item.name){
case "name1": return <InputBox/>;
case "name2": return <SelectBox/>;
case "name3": return <<SelectBox/>;/>;
default: return <InputBox/>
}
</div>
))}
</div>
);
In React, a switch statement is one of the best ways to handle conditional rendering. For instance, you might want to render a specific component based on users' inputs. You can store the value of input fields in the state and examine the state value to determine the right component to render.
The "Expression expected" TypeScript error occurs when we have a syntax error in our code or our code editor is using an older version of TypeScript. To solve the error, make sure to correct and syntax errors and use a recent version of the TypeScript compiler.
(three dots in JavaScript) is called the Spread Syntax or Spread Operator. This allows an iterable such as an array expression or string to be expanded or an object expression to be expanded wherever placed. This is not specific to React. It is a JavaScript operator.
We can embed any JavaScript expression in JSX by wrapping it in curly braces. But only expressions not statements, means directly we can not put any statement (if-else/switch/for) inside JSX.
If you want to inline a switch statement, you need to encase it inside an IIFE.
export default ({handle, state}) => (
<div style={styles.container}>
<h3 style={{margin: 0, marginBottom: 15}}>InputData</h3>
{items.map((item) => (
<div style={styles.lineContainer}>
{(() => {
switch(item.name) {
case "name1": return <InputBox/>;
case "name2": return <SelectBox/>;
case "name3": return <SelectBox/>;
default: return <InputBox/>
}
})()}
</div>
))}
</div>
);
You have to use your switch statement in a function. Also, for clarity sake, you would be better off trying to keep conditional logic like that outside of your immediate component body.
export default function({ handle, state }) {
function renderSwitch(item) {
switch (item.name) {
case "name1":
return <InputBox />
case "name2":
return <SelectBox />
case "name3":
return <SelectBox />
default:
return <InputBox />
}
}
return (
<div style={styles.container}>
<h3 style={{ margin: 0, marginBottom: 15 }}>InputData</h3>
{items && items.map(item => <div style={styles.lineContainer}>{renderSwitch(item)}</div>)}
</div>
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With