본문 바로가기

Web Dev/react.js

React.js 라우팅 된 각각 페이지에 한개의 useState 변수 전달하기

반응형

 

App.js

import { Route, Routes } from 'react-router-dom';
import React, { useState } from 'react'
import './App.css';
import Test from './Test';
import Heading from './Component/Heading';
import List from './Component/List';
import Upload from './Component/Upload';

function App() {

  const [ContentList, setContentList] = useState([]);


  return (
    <>
      <Heading />
      <Routes>
        <Route path='/' element={<Test />} />
        <Route path='/list' element={<List ContentList={ContentList} setContentList={setContentList} />} />
        <Route path='/upload' element={<Upload ContentList={ContentList} setContentList={setContentList} />} />
      </Routes>

    </>

  );
}

export default App;
 
  const [ContentList, setContentList] = useState([]);

해당 값을 props로 전달하면 된다. 

Upload.js

import { React, useState } from 'react'

const Upload = (props) => {

    const [Content, setContent] = useState("");


    const onSubmit = () => {
        let Arr = [...props.ContentList];
        Arr.push(Content);
        props.setContentList([...Arr])
        //새로운값 입력해야지 
        setContent("")
    }


    return (

        <>
            <div className='test'> Upload Component

                <input
                    type="text"
                    value={Content}
                    onChange={
                        (e) => { setContent(e.currentTarget.value) }} />


                <button style={{ marginTop: "1rem" }} onClick={() => {
                    onSubmit();
                }}>제출</button>

            </div>




        </>
    )

}

export default Upload;

List.js

import { React, useState } from 'react'

const List = (props) => {





    return (
        <>
            <div className='test'> List Component</div>
            <div>
                {props.ContentList.map((content, index) => {
                    return (
                        <div
                            key={index}
                            style={{ width: "100%", marginLeft: "1rem" }}>
                            내용 : {content}
                            <hr />
                        </div>)
                })}</div>

        </>

    )
}

export default List;

 

props 변수로 받아서 

prop.setContentList 

이처럼 사용하면 된다. 

반응형