简体   繁体   中英

Passing an Object as Props ReactJS

I have basically a two steps form, and it's are divided in switchable tabs. The user needs to be able to go from one tab to another without losing the info already filled. So I need to find a way to prevent React from nullifying my states.

First form Component:

const initialValues = {
  nome: "",
  cpf: "",
  email: "",
  telefone: "",
  nomeResp: "",
  cpfResp: "",
};

const 1Form = (props) => {
  const [values, setValues] = useState(initialValues);
  const handleChange = (e) => {
    setValues({ ...values, [e.target.name]: e.target.value });
  };
....

I would receive the state at the father component and send it to the other component and save it as an object state. I thought that maybe if I had a big state that would receive all the states from both forms, I could send this big state from one component to another...

....    
         <SwipeableViews index={value} onChangeIndex={handleChangeIndex}>
            <TabPanel value={value} index={0}>
              <1Form bigState={bigStateValue}/>
            </TabPanel>
            <TabPanel value={value} index={1}>
              <2Form bigState={bigStateValue}/>
            </TabPanel>
          </SwipeableViews>
....

When you want to share state between sibling components, the first thing to try is to use a concept called state lifting . Basically it consists in lifting the state up to the closest common ancestor of the sibling components (I could see you were thinking in something pointing to this direction).

Now, since your state belongs to the parent component you need to pass a callback function to you form so you can update the state from inside the form components.

It would look something like this:

// Pseudo code
function Parent() {
  const [state, setState] = useState({})
  
  function handleChange() {
    // updates data
  }

  return (
    <Form1 data={state} onChange={handleChange} />
    <Form2 data={state} onChange={handleChange} />
  )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM