Reputation: 5379
I've got an array full of numbers 1, 2, 3. I'm trying to map over it for each number to render a Square component. This worked fine. Now I want to conditionally style the Square component depending on the value (1, 2 or 3). I've got a syntax error on the line with 'switch' (Unexpected token) that I can't seem to spot the reason for.
class MainMaze extends Component {
generateMaze() {
const { tiles, cols, rows } = this.props.grid;
return (
tiles.map((sq, i) =>
switch (sq) {
case 3:
return <Square style={{ backgroundColor: 'red' }}>{sq}</Square>;
case 2:
return <Square style={{ backgroundColor: 'blue' }}>{sq}</Square>;
default:
return <Square style={{ backgroundColor: 'green' }}>{sq}</Square>;
}
);
}
render() {
const { grid, position, status } = this.props;
return (
<View>
<CardSection>
<Text>{grid.cols}</Text>
</CardSection>
<CardSection>
{this.generateMaze()}
</CardSection>
</View>
);
}
}
const mapStateToProps = (state) => {
return {
status: state.status,
position: state.position,
grid: state.grid
};
};
export default connect(mapStateToProps)(MainMaze);
the Square component:
import React from 'react';
import { View, Text } from 'react-native';
const Square = (props) => {
return (
<View style={[styles.containerStyle, props.style]}>
<Text>
{props.children}
</Text>
</View>
);
};
const styles = {
containerStyle: {
borderWidth: 1,
borderColor: '#ddd',
elevation: 1,
alignItems: 'center',
justifyContent: 'center',
margin: 0,
height: 30,
width: 30
}
};
export { Square };
Upvotes: 1
Views: 1846
Reputation: 4201
Here is the correct syntax of an arrow expression function with multiple statements (taken from mozilla docs):
(param1, param2, …, paramN) => { statements }
ie, you should wrap the switch
block with {...}
:
generateMaze() {
const { tiles, cols, rows } = this.props.grid;
return (
tiles.map((sq, i) => {
switch (sq) {
case 3:
return <Square style={{ backgroundColor: 'red' }}>{sq}</Square>;
case 2:
return <Square style={{ backgroundColor: 'blue' }}>{sq}</Square>;
default:
return <Square style={{ backgroundColor: 'green' }}>{sq}</Square>;
}
}
))
}
Upvotes: 1