Answer the question
In order to leave comments, you need to log in
React: How to transfer data from an object to another component?
Good afternoon, I ran into a problem transferring data from an object to other components.
const data = [
{
link: 'User 1',
text: ' Lorem ipsum dolor sit amet, consectetur adipisicing elit.,
id: '1',
img: '',
position: 'Web Developer',
},
{
link: 'User 1',
text: ' Lorem ipsum dolor sit amet, consectetur adipisicing elit.,
id: '2',
img: '',
position: 'Web Developer',
},
{
link: 'User 2,
text: ' Lorem ipsum dolor sit amet, consectetur adipisicing elit.,
id: '3',
img: '',
position: 'Web Developer',
}
];
<Switch>
<Route exact path="/messages" component={AppMessages}/>
<Route path="/messages/chat" component={AppMessageItems}/>
<Route path={["/messages/chat", "/messages/chat/:id"]} component={AppMessageItems} />
</Switch>
const AppMessages = () => {
return (
<Container>
<AppChatList>
{data.map(function(item, index) {
return (
<li key={index}>
<Link to={`/messages/chat/${item.id}`}>
<AppMessageUserList {...item} />
</Link>
</li>);
})}
</AppChatList>
</Container>
);
};
const AppMessageItems = (props) => {
const { text } = props;
return (
<Container>
<div>
ID: { id}
</div>
</Container>
)
};
Answer the question
In order to leave comments, you need to log in
If you have the same data rummaged between different pages, this data will quite pass for the global state of the application.
There are several ways to store and change it:
a) store data in the context and get it and a method for changing it by connecting to the context (see useContext or contextType, depending on the functionality / class of the component).
b) use third-party state management solutions. A choice of redux, mobx, effector and other libraries.
You can put it data
in context, and access it wherever you want with the help of useContext
.
And then something like this will happen:
const AppMessageItems = () => {
const { id } = useParams(); // react-router-dom hook
const subset = useContext(YourContextName).find(item => item.id === id);
return (
<Container>
<div> Id: {subset.id}</div>
<div> Text: {subset.text}</div>
...
</Container>
);
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question