Reputation: 31
How does one go about dynamically rendering a stateful component that takes in props that can change after render? I have tried storing components in state and then mapping out the state however the components do not update when the props passed into them has changed. Example:
export default App(props){
const [name, setName] = useState(null)
const [articles, setArticles] = useState([])
return (
{articles.map((article) => {article})}
<input type="text" value={name} onChange={e => setName(e.target.value)}/>
<button type="button" onClick={() => setArticles([...articles, <Article name={name}/>])}}>Add Article</button>
)
}
export default Article(props){
return (
<p>props.name</p>
)
}
In my example, when I update the name state by changing the input field, none of the rendered articles update to reflect this change, only new additions when the add article button is pressed after the name has been changed, I want them to update as the state changes, how do I do this?
Upvotes: 0
Views: 156
Reputation: 6088
This is a clean-up of your code that basically produces a "To Do" list. Some mistakes you had...
default
exportsmap
props.name
export default function App(props){
const [name, setName] = useState(null)
const [articles, setArticles] = useState([])
return (
<>
{articles}
<input type="text" value={name} onChange={e => setName(e.target.value)}/>
<button type="button" onClick={() => setArticles(
[...articles, <Article name={name}/>]
)}>Add Article</button>
</>
)
}
export function Article(props){
return (
<p>{props.name}</p>
)
}
Upvotes: 1