일단 nav 컴포넌트를 만들어야 한다. 위에 있는 nav바 이다.
이런식으로 만들어야 한다. nav바에 있는 0은 현재 진행한 습관이 추가되면 1 추가되게끔 만들면 된다.
일단 nav바에도 count가 있어야 하기 때문에, 모든 데이터(state)를 최상위 컴포넌트인 app 컴포넌트에 옮겨야 한다.
app.jsx
class App extends Component {
state = {
habits: [
{ id: 1, name: "Reading", count: 0 },
{ id: 2, name: "Running", count: 0 },
{ id: 3, name: "Coding", count: 0 },
],
};
handleIncrement = (habit) => {
// state 오브젝트 안에 있는 count 를 증가한 뒤 state를 업데이트 해야 함
const habits = [...this.state.habits];
const index = habits.indexOf(habit);
habits[index].count++;
this.setState({ habits });
};
handleDecrement = (habit) => {
// state 오브젝트 안에 있는 count 를 증가한 뒤 state를 업데이트 해야 함
const habits = [...this.state.habits];
const index = habits.indexOf(habit);
const count = habits[index].count - 1;
habits[index].count = count < 0 ? 0 : count;
this.setState({ habits });
};
handleDelete = (habit) => {
const habits = this.state.habits.filter((item) => item.id !== habit.id);
this.setState({ habits });
};
habits.jsx에 있던 것을 app.jsx로 옮겼다.
그 후 이제 habits.jsx에서는 app의 props로 받아야 한다.
habits.jsx
import React, { Component } from "react";
import Habit from "./habit";
class Habits extends Component {
handleIncrement = (habit) => {
this.props.onIncrement(habit);
};
handleDecrement = (habit) => {
this.props.onDecrement(habit);
};
handleDelete = (habit) => {
this.props.onDelete(habit);
};
render() {
return (
<ul>
{this.props.habits.map((habit) => (
<Habit
key={habit.id}
habit={habit}
onIncrement={this.handleIncrement}
onDecrement={this.handleDecrement}
onDelete={this.handleDelete}
/>
))}
</ul>
);
}
}
export default Habits;
this.state 였던 것을 this.props.habits로 변환 후 handle 이벤트들도 props로 받아온다.
habit.jsx 컴포넌트는 그냥 그대로 놔두면 된다.
이제 nav컴포넌트를 만들어보자. navbar.jsx 컴포넌트를 만든다.
import React, { Component } from "react";
class Navbar extends Component {
render() {
return (
<nav className="navbar">
<i className="fa-solid fa-leaf" id="navbar-logo"></i>
<span>Habit Tracker</span>
<span className="navbar-count">{this.props.totalCount}</span>
</nav>
);
}
}
export default Navbar;
이렇게 기본적인 구성을 한다. this.props.totalCount로 count 를 props로 받는다.
navbar는 app.jsx를 props로 받을 것이기 때문에 app에서 props를 지정해주면 된다.
app.jsx
render() {
return (
<>
<Navbar
totalCount={this.state.habits.filter((item) => item.count > 0).length}
/>
<Habits
habits={this.state.habits}
onIncrement={this.handleIncrement}
onDecrement={this.handleDecrement}
onDelete={this.handleDelete}
/>
</>
);
}
}
이렇게 return에 navbar를 불러온 후, totalCount를 props 인자로 받게끔 만들어준다.
totalCount는 따로 함수 작성 필요 없이 그냥 filter를 사용해서 item.count가 0보다 클 시 그 길이의 값을 배열로 새로 생성해주도록 만들어준다.
'React' 카테고리의 다른 글
react reset 버튼 만들기 (0) | 2022.09.07 |
---|---|
react input / add form 컴포넌트 만들기 (0) | 2022.09.07 |
react 이벤트 처리하기 (0) | 2022.09.07 |
react Habits 컴포넌트 만들기 (state up, list key) (0) | 2022.09.06 |
react state, props (0) | 2022.09.06 |