when i got an value passed by params to be setted in useState already declared with default value first it render with the previous (default) value then render with new value that i'm passing in params .. is there is a possible way to render only after recieving the new value !? if i wasn't clear to describe my issue please don't hesitate to ask me for more details .. thanks in advance .
trying to set useState with new value expecting component render after recieving new value and not ernder with the default value.
CodePudding user response:
If you could provide a snippet of your code that could help.
You could provide a child component with initial state like this:
const ParentComponent = () => {
const [initialValue, setInitialValue] = useState("Initial value")
return <ChildComponent key={initialValue} initialValue={initialValue} />
}
const ChildComponent = ({ initialValue }) => {
const [inputValue, setInputValue] = useState(initialValue)
return <input value={inputValue} onChange={handleChange} />
}
The key
attribute on the child component will force react to create a new instance every time the initialValue
changes. This should also render the component exclusively with the state you pass it.
This will work for small components, but if you are, for example, fetching data or handling complex logic in the child component, you should definitely handle the state within the child component.
You can also not render the component if the state is, for example, null
by using a ternary operation in the return section:
// ...
return initialValue ? (
<input value={inputValue} onChange={handleChange} />
) : null
// ...
CodePudding user response:
Please use the below render logic
class TestComponent extends React.Component
{
render(){
const {data}=this.props;
return(<Fragment>
{(data?<div>{data.id}</div>:null)}
</Fragment>);
}
}