일반 html에서 DOM 요소에 이름을 달 때는 id 를 사용
<div id=”my element”> </div>
src/index.js 파일 중에 id가 root인 요소에 react component를 rendering하는 코드 있음
...
const root = ReactDOM.createRoot(document.getElementById('root')); // here!
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
reportWebVitals();
Reference?
이와 같이 HTML에서 id를 사용하여 DOM에 이름을 다는 것 처럼 react에서도 프로젝트 내부에 DOM 이름 다는 방법!
When to use Reference?
→ DOM을 직접적으로 건드려야 할 때
Example
Process
- Validation Sample component 만들기
- button 누를 때 마다 input에 fous 추가
// src/ValidationSample.css
.success {
background-color: : lightgreen;
}
.failure {
background-color: lightcoral;
}
// src/ValidationSample.js
import React, { Component } from 'react'
import '/ValidationSample.css';
class ValidationSample extends Component {
state = {
password: '',
clicked: false,
validated : false
}
handleChange = (e) => {
this.setState({
password: e.target.value
});
}
handleButtonClick = () => {
this.setState({
clicked : true,
validated: this.state.password === '0000'
})
}
render() {
return (
<div>
<input type='password'
value={this.state.password}
onChange={this.handleChange}
className={this.state.clicked ? (this.state.validated ? 'success' : 'failure') : ' '}></input>
<button onClick={this.handleButtonClick}>검증하기 </button>
</div>
)
}
}
export default ValidationSample;
DOM을 꼭 사용해야하는 상황
How to use ref?
props 설정하듯 ref 값으로 callback 함수 전달
<input ref={(ref) ⇒ {this.input=ref}}></input>
this.input은 input의 요소의 DOM을 가리킴
Component에 Ref 달기
주로 컴포넌트 내부에 있는 DOM을 컴포넌트 외부에서 사용시 씀
<MyComponent ref={(ref) => {this.myComponent = ref}}/>
MyComponent 내부 method 및 멤버변수에도 접근 가능, 내부 ref 접근 가능 like handleClick, input등
ex. Scrollbox Component 만들기 → 컴포넌트에 ref달기 → ref이용해서 컴포넌트 내부 메소드 호출
// App.js
import logo from './logo.svg';
import './App.css';
import React, {Component} from 'react';
import ScrollBox from './ScrollBox';
class App extends Component {
render() {
return (
<div>
<ScrollBox ref={(ref) => this.scrollBox=ref}/>
<button onClick={() => this.scrollBox.scrollToBottom()}>맨 밑으로</button>
</div>
);
}
}
export default App;
// ScrollBox.js
import React, {Component} from 'react';
class ScrollBox extends Component {
render(){
const style = {
border : '1px solid black',
height : '300px',
width : '300px',
overflow : 'auto',
position : 'relative'
};
const innerstyle = {
width : '100p%',
height : '600px',
background: 'linear-gradient(white,black)'
};
scrollToBottom = () => {
const {scrollHeight, clientHeight } = this.box;
this.box.scrollTop = scrollHeight- clientHeight;
} //비구조화 할당 문법 사용
return (
<div style={style}
ref={(ref)=> {this.box=ref}}><div style={innerstyle} />
</div>
)
}
}
export default ScrollBox;