Home > Software engineering >  Re-ender child component everytime there is a change in props value
Re-ender child component everytime there is a change in props value

Time:03-04

I have made a page of 2 components - Form component & preview component. One part is a form component with a message field and on the other side the same message is previewed in an interface to show how that message will be used in the product.

In the Home.js, on the leftside, I call a re-usable form component that handles all change, submit events. From this re-usable form component, I call this function to get the value of message in home.js

  const getInputValue=(data)=>{
     messageValue = data.message;
    }

So I get current state of Input in messageValue. From here, I pass the messageValue to preview component via props.

See the entire Home.js below :

function HomePanel(props) {

var messageValue;

  const getInputValue=(dataduplicate)=>{
     messageValue = dataduplicate.message;
    }


const getrightcontent =()=>{
  
  if(item ==="select1")
 ..do this...
  
  if(item ==="select2")
  return (<SimplePreview  messageValue={messageValue} closeImage={closeImage} company={company}/>)


return (
<div>
{getleftcontent()}
</div>
        
<div>
{getrightcontent()}
</div>
       
     
    );

}


My simple preview component looks like this :


function SimplePreview({messageValue,closeImage, company}) {

return(
<div className="Preview_message">
<p>{messageValue}<p>
</div>       
)
}

I want to preview the live messageValue here in this component. So i was wondering, how to render the element. Right now I get empty value because when it is rendered, messageValue is empty. When I do console.log(messageValue) in home.js, I get live messageValue with every change.

I have almost 2 days on this.I'm new to programming. So would really appreciate any sort of help.

CodePudding user response:

messageValue is recomputed on every render and therefore empty every time. In order to persist data from one render to the other, use the useState hook:

import {useState} from 'react';

function HomePanel(props) {

const [messageValue, setMessageValue] = useState("");

  const getInputValue=(dataduplicate)=>{
     setMessageValue(dataduplicate.message);
    }


const getrightcontent =()=>{
  
  if(item ==="select1")
 ..do this...
  
  if(item ==="select2")
  return (<SimplePreview  messageValue={messageValue} closeImage={closeImage} company={company}/>)
}

return (
<>
<div>
{getleftcontent()}
</div>
        
<div>
{getrightcontent()}
</div>
</>
     
    );

}

CodePudding user response:

Your messageValue is not a part of React's state management which is mainly for UI re-rendering.

On top of the component you need to import useState

import React, { useState } from 'react'

After that, you can call it into your function

const [messageValue, setMessageValue] = useState

const getInputValue=(dataduplicate)=> {
   setMessageValue(dataduplicate.message;)
}
  • Related