Props는 부모 컴포넌트로부터 자식 컴포넌트에 데이터를 보낼 수 있게 해주는 일종의 방법입니다.
props는 첫 번째이자 유일한 인자이며, 객체object입니다.
아래의 예제 코드는 한개의 버튼 컴포넌트로 save changes 와 continue 텍스트를 가지고 있는 두개의 버튼이 화면에 출력됩니다.
function Btn(props) { // Btn({ text = 'text'}) 로 사용해 줄 수 있음
// 'text'는 기본값
return (
<button style={{
backgroundColor: 'tomato',
color: 'white',
padding: '10px 20px',
border: 0,
borderRadius: 10,
}}>
// 위의 주석처럼 가져오면 props 생략가능 {text}
{props.text} // 📌 text 값을 가져와서 사용해줌
</button>
)
}
function App() {
return (
<div>
<Btn text='save changes '/> // 📌 안에 내용은 전부 props로 전달됨
<Btn text='continue' />
</div>
);
}
const root = document.getElementById('root');
ReactDOM.render(<App />, root)
React Memo 라고 불리는 기능으로 props가 바뀌지 않는 부분(상태가 변하지 않는 부분)은 재 랜더링 하는걸 막아줄 수 있습니다.
const MemorizedBtn = React.memo(Btn) // 📌 Btn 함수를 넣어줌
function App() {
const [value, setValue] = React.useState('save changes')
const changeValue = () => setValue('revert changes')
return (
<div>
<MemorizedBtn text={value} changeValue={changeValue} /> // 📌
<MemorizedBtn text='continue' /> // 📌
</div>
);
}
props type(string, number, boolean ...)을 지정해 줌으로써 정확한 props 전달이 가능하도록 오류를 찾아줄 수 있습니다.
Btn.propTypes = {
text: PropTypes.string,
// 📌 isRequired가 붙으면 무조건 사용되어야 함
fontSize: PropTypes.number.isRequired
}
function App() {
const [value, setValue] = React.useState('save changes')
const changeValue = () => setValue('revert changes')
return (
<div>
<Btn text={value} changeValue={changeValue} fontSize={18} />
// 📌 fontSize 를 가지고 있지 않음으로 콘솔창에 오류가 뜸
<Btn text='continue' />
</div>
);
}