Files

107 lines
2.4 KiB
Markdown
Raw Normal View History

2018-10-12 15:37:13 -04:00
---
title: Change Inline CSS Conditionally Based on Component State
---
# Change Inline CSS Conditionally Based on Component State
2018-10-12 15:37:13 -04:00
---
## Hints
### Hint 1
2018-10-12 15:37:13 -04:00
You are going to be checking the length of ```this.state.input``` so use its ```.length``` property.
2018-10-12 15:37:13 -04:00
```javascript
this.state.input.length;
2018-10-12 15:37:13 -04:00
```
### Hint 2
2018-10-12 15:37:13 -04:00
You are entering code before the return statement so you can use a pure JavaScript ```if/then``` statement.
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
2018-10-12 15:37:13 -04:00
You will use an ```if/then``` statement to check the value of ```this.state.input.length```. If it is longer than 15, assign ```'3px solid red'``` to ```inputStyle.border```.
```jsx
class GateKeeper extends React.Component {
constructor(props) {
super(props);
this.state = {
input: ''
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({ input: event.target.value })
}
render() {
let inputStyle = {
border: '1px solid black'
};
// change code below this line
if (this.state.input.length > 15) {
inputStyle.border = '3px solid red';
}
// change code above this line
return (
<div>
<h3>Don't Type Too Much:</h3>
<input
type="text"
style={inputStyle}
value={this.state.input}
onChange={this.handleChange} />
</div>
);
}
};
```
</details>
<details><summary>Solution 2 (Click to Show/Hide)</summary>
2018-10-12 15:37:13 -04:00
Write a conditional statement that is evaluated according to your state, as mentioned in the challenge description, checks the length of the input and assigns a new object to the inputStyle variable.
```jsx
class GateKeeper extends React.Component {
constructor(props) {
super(props);
this.state = {
input: ''
};
this.handleChange = this.handleChange.bind(this);
2018-10-12 15:37:13 -04:00
}
handleChange(event) {
this.setState({ input: event.target.value })
}
render() {
let inputStyle = {
border: '1px solid black'
};
// change code below this line
if (this.state.input.length > 15) {
inputStyle = {
border: '3px solid red'
};
}
// change code above this line
return (
<div>
<h3>Don't Type Too Much:</h3>
<input
type="text"
style={inputStyle}
value={this.state.input}
onChange={this.handleChange} />
</div>
);
}
};
2018-10-12 15:37:13 -04:00
```
</details>