Skip to content Skip to sidebar Skip to footer

How To Send Props In Class Component To Functional Component?

I am beginner to reactjs. need to know how to send the props values in one page to another page. Props are on the first page I can get the class component value how to get the valu

Solution 1:

opinion, but this is i would've done it... :)

this.state = {
 background: 'color',
 pickedWall: false,
}

const handleChangeComplete = (e) => {
 this.setState(prevState => ({
  ...prevState,
  pickedWall: true,
  background: e.target.value,
 }))
}

render() {
 const { x, y } = this.props     
 const { background, pickedWall } = this.state
 const { handleChangeComplete } = thisreturn <SketchPicker {...{ x, y, background, handleChangeComplete, pickedWall }} />
}

and in your component...

constSketchPicker = ({
 x,
 y,
 background,
 pickedWall,
 handleChangeComplete,
}) => {
 return (
  <div><SomeDivonClick={(e) => handleChangeComplete(e)}>
    ...your code
   </SomeDiv><Fragment>
    {pickedWall && <WallPicker {...{ x, y, background }} />}
   </Fragment></div>
 )
}

Solution 2:

You could either use React Hooks or any other state management library like Redux, MobX etc. In React, if there is no immediate relationship(parent-children) between two components you can connect these two with a global state. A global state in simple words is an object that can be accessed by many components using connectors or Flux technics.

Solution 3:

Actually your child component will get mounted, as soon as your current component is rendered. So whatever the value after the render will not affect the previously rendered child component.

this.state = {
    backgroundColor: 'aqua';
}

So <WallFactory background={this.state.background}/> will contain aqua.

If you need to pass a different background to the child, pass a function to the child like

<WallFactory getBackgroundColor={this.passbackgroundColor}/>

passbackgroundColor() {
    returnthis.state.backgroundColor
}

in the child component

const backgroundColor = props.getBackgroundColor();

if you really need this to be dynamic.

Post a Comment for "How To Send Props In Class Component To Functional Component?"