Home > Net >  Can we pass props from Parent to Child component in React, and set the props as state of child compo
Can we pass props from Parent to Child component in React, and set the props as state of child compo

Time:07-02

const Parent=()=>{ return( ) }

const Child=({data})=>{ return ( {data} ) }

Can I set the props in Child component to its state?

CodePudding user response:

Yes you can. Something like:

class Child extends Component {
  constructor(props){
  const {myProp} = props;
  this.state = {myNumber: myProp}

  render(){
  const {myNumber} = this.state;
  return <div>{myNumber}</div>
}

class Parent extends Component {
  render () {
  return <Child myProp={5} />
  }
}

BUT: if your "parent" component refreshes, so does the child and the state is reverted back to the value set by the parent, and all the state changes you did on the child are lost.

CodePudding user response:

Yeah here made a code sandbox example showing how to do it: https://codesandbox.io/s/stack-pass-props-fgq67n

Child component looks like this

const Input = ({ string }) => {
  const [value, setValue] = useState(string);

  return <input value={value} onChange={(e) => setValue(e.target.value)} />;
};

Parent Component:

export default function App() {
  return (
    <div className="App">
      <Input string="default" />
    </div>
  );
}

Sometimes if the parent reloads the passed props may reset to defaults

CodePudding user response:

There is a concept in React known as controlled and uncontrolled components, When your component only have props and no state inside itself then it a controlled component, that is controlled by the parent component.

Also, it is not advisable to convert the props to the state of the child component, if you want to change the value of the props, just pass an additional method as a props which will be called by the Child to update the value of the props, let show you with an example

const Parent = () => {
   const [number, setNumber] = useState(0);
   const updateNumberHandler = (numberToUpdate) => setNumber(numberToUpdate)
   return <Child number={number} onUpdateNumber={updateNumberHandler} />
}


const Child = (props) => {
  const { number, onUpdateNumber } = props;
  return <button onClick={() => onUpdateNumber(number   1)}>Updated Number: {number}</button>
}

Here you can see I am passing two props one value and one method to update that value, when the onUpdateNumber method is called the value on the parent is updated so it gets re-render and also the child gets re-render with the updated number value.

  • Related