Reputation: 3860
Sorry for the vague title. I struggled thinking about a title that would be descriptive of the problem I am facing.
I want to create a box with a limited width and a hidden overflow so that as you continue pressing buttons (digits), you see the new digits you are pressing and the digits that were pressed in the past are now hidden from view.
For example, let's say we have a box that can hold 5 digits. At first I press 1, then 3, 9, 4, and 5, showing me:
13945
If I next press 6 and 2 I would want to be shown:
94562
How do I achieve this styling given the component below? Thanks!
class App extends React.Component {
constructor() {
super();
this.state = {
digits: 0
}
this.handleClick = this.handleClick.bind(this);
}
handleClick(event) {
this.setState({digits: this.state.digits + event.target.value });
}
render() {
return (
<div>
<div id="digits">{this.state.digits}</div>
<input value={this.state.digits} />
<button onClick={this.handleClick} value={1}>1</button>
<button onClick={this.handleClick} value={2}>2</button>
<button onClick={this.handleClick} value={3}>3</button>
<button onClick={this.handleClick} value={4}>4</button>
<button onClick={this.handleClick} value={5}>5</button>
</div>
);
}
}
ReactDOM.render(<App />, app);
#digits {
border: 2px solid red;
width: 40px;
overflow: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="app"></div>
Upvotes: 1
Views: 158
Reputation: 1377
For your solution, you need to remove the first digit before adding a new one. I am assuming that the digits variable is a string.
handleClick(event) {
// Removes the first number from the digits.
var newDigits = this.state.digits.substr(1);
this.setState({digits: newDigits + event.target.value });
}
Upvotes: 2
Reputation: 176
If you want to keep all of the digits in the HTML, you could nest another container for the digits inside your #digits
container that would not have a set width and simply float it to the right.
css:
#digits {
border: 2px solid red;
width: 40px;
overflow: hidden;
}
#digits div {
float:right;
}
react component html:
<div id="digits">
<div>{this.state.digits}</div>
</div>
Otherwise it might be best/reactive to push() and pop() the digits as needed, as suggested in the comments.
Upvotes: 3