React and navigating to a selected item - javascript

I have a table of user I am displaying to a user. They click a row, and I want to navigate to a component to show the details.
<tbody>
{this.state.clients.map(client => (
<tr className="tableRow" onClick={() => this.handleSelection(client.id)}>
<td>{client.name}</td>
My Route is setup like this:
<Route path="/client/:clientId" component={Client} />
So in the row, I have an onClick event, which calls a function, passing the parameter selected. Here's the function:
handleSelection(clientId) {
this.props.history.push(`/client/${clientId}`);
}
Then, in the constructor of the target component, I am just logging the selected id, which will be passed to the api to load the data:
console.log('Loading clientId...', this.props.match.params.clientId);
But this seem wrong. I get the right ID and all, but .. am I doing this right? Is there a better/safer way to do what I am doing?

Another option would just be to use individual Link tags inside each TD:
<td><Link to={`/client/${client.id}`}>{client.name}</Link></td>
That would also be more accessible, since vision impaired users might have trouble triggering that onclick event.

If you're using react-router-dom it has a Link component
{this.state.clients.map(client => (
<Link to={`/client/${clientId}`} >
<tr className="tableRow">
<td>{client.name}</td>
</Link>
It's better to use a link rather than an onClick on on a table row for accessibility.
If you're not using react-router-dom you can roll your own version from looking at the source - https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/modules/Link.js
By working in this way it'll behave correctly when people command click on the link to open it in a new tab.
For the routes you grab the params as you have, if you don't want the component to deal with match in the properties you can do something like this:
<Route path="/client/:clientId" children={({ match }) => (<Client {...match.params} />)} />

Related

Storage-design for fetched data (globally?) & navigation

im new to JavaScript & React (and new to stackoverflow too) and I hope to get some ideas/ answers regarding the "logic" in implementing data-storage. I have/ had a dev-background in Obj-C / iOS few years back. So some general concepts in web-dev might not be familiar to me.
Hope I'm doing everything correct in my first post, never really used stackoverflow so far :)
So, basically I have a small project with a Sider und Content (using Ant Design Framework). In this project, im trying to figure out, how generell stuff has to be done, like Navigation through the views, data handling and so on.
In one Tab in the SideBar, i'm using a Table (also antd). If you press on one Item, it should show a detail-View with the props of that specific item (later it should be the form for data change/input).
My App.js:
<Content style=...>
<Switch>
<Route exact path="/tasks" >
<TasksTable
data={this.state.tasksData}
handleOnRowClicked = {this.handleOnRowClicked}
/>
</Route>
<Route exact path="/details">
<TasksDetail currentTask= {this.state.currentDetailTask}/>
</Route>
....
</Switch>
</Content>
In the TasksTable-Component:
...
const history = useHistory()
...
function handleOnRowClicked(record, rowIndex,event) {
console.log("Clicked on cell", event)
history.push("/details/")
props.handleOnRowClicked(record.id)
}
return(
<Table
dataSource={props.data}
onRow={ (record, rowIndex) => {
return {
onClick: event => {
handleOnRowClicked(record, rowIndex,event) }
}
}
}
>
<Column title="Name" dataIndex="name" key="name" />
<Column title="Kunde" dataIndex="client_name" key="client_name" />
<Column title="Fertigstellung bis" dataIndex="completion_date" key="completion_date" />
<Column title="HinzugefĆ¼gt" dataIndex="created" key="created" />
<Column title=""
dataIndex="remove_button"
key="remove_button"
render={removeButton => {
return <button key="ButtonKey" onClick={event => handleOnButtonClicked(event)}>Remove</button>
}}/>
</Table>
)
}
What i want to achive:
When clicked on one row of the table, i want to push another "view"/ Side to show details of selected row. Currently I'm doing this in the TasksTable-Component with history.push(). I'm wondering if this is the correct way of showing (detail-)views? Because I need to call props.myHandleCallbackFunc(selectedItem) in App.js to set a State names "currentlySelected" for then passing this state as prop to the pushed detail view.
Hope you get my point.
As far as I understood, I should use ... for automating the navigation-process. Problem is: As I use the Table from antdesign, I need to make this programatically. Thats why I have this workaround (at least it feels like one) with the onRow property... Is this the correct way of using the table? I have the feeling its not.
Problem with my workaround: I've rendered a Button into the Cells to deliver a delete-Button.
Problem there: Even if i click on the Button, it is registered as a click on the row and therefor pushes my detailview... I tried to differentiate with event.target.key but had no success.
Is it the right way of holding all data fetched by my api in the uppermost component and share it to sup-components via props? How can I update it from subcomponents then? Should every Subcomponent should get a handler via props to call back, when value changed?
Or in other words: Make the http-request from the sub-comp or send the changed data to the App-component and let it then trigger the HTTP-POST-request? I strongly guess its second choice.
Thank you so much, I appreciate every answer. Im trying to get things working since few hours now...
(Sorry for spelling mistakes, english is not my native one).
P.S: Actually I wanted to post this yesterday but took few extra hours for working through the "similar questions"... Still, open questions :D
Robin
Redux is a predictable state container for JavaScript apps.
It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test. On top of that, it provides a great developer experience, such as live code editing combined with a time traveling debugger.
You can use Redux together with React, or with any other view library. It is tiny (2kB, including dependencies), but has a large ecosystem of addons available.
https://redux.js.org/introduction/getting-started

React component not reloading on history.push

I have an app with routes defined as follows:
<Route exact path="/:category/:product" component={ProductComponent} />
On category page, "/:category I have two buttons for each product, "Quick View" and "Full view", on click of which I want to move to product page, but also set the state for view like setView('quick') or setView('full').
I tried solving this by using onclick on buttons with the following code:
() => {
setView('quick')
history.push(`/${category.slug}/${product.slug}`)
}
here both are called, history api changes the url but component does not load for that url. I cannot use the react-router's <Link> component because I need to set the view before going to product page.
How can I use the history from react-router to perform page change like <Link> does?
Try this
Remove component and use render
<Route
exact
path="/:category/:product"
render={({ match }) => <ProductComponent key={match.params.product || 'empty'} />}
/>

React Fontawesome Icon on Button not Allowing Id to be Accessed

I am using react fontawesome in my project. Under the render function of my component I have the following which maps a school onto the page and then I want a button with an edit icon to perform an action. My code for the button looks as below:
{ this.state.myschools.map( (school) => (
<Row key={school.id}>
<Col><p>{school.name}</p></Col>
{ school.deaths.length > 0 ? <Col md="2"><button id={school.id} className="likelink" onClick={this.goToSchoolDeathList}>View Deaths</button></Col> : <Col md="2"></Col> }
<Col><button id={school.id} onClick={this.editSchool}><FontAwesomeIcon icon={faEdit} /></button></Col>
</Row>
))}
The editSchool function is as:
editSchool(e) {
console.log("School Id");
console.log(e.target.id);
}
If I click on the empty space around the font awesome icon then the id is logged to the console. If I only click on the area where the icon exits then the id is not logged. I want the user to be able to click on any part of the button including the fa icon and to capture the school id.
I have tried adding the onClick event and the id attribute to the "FontAwesomeIcon" component, but that still doesn't work.
Can anyone help?
Well, this is one of the common pitfall you learn during your time with React. Rest assure, we have all fallen into this pit.
There are few AHA moments here.
1st Aha: React doesn't have a usual way to let you get element attribute in an event (an e in your example).
That being said, you can still access to the button element by e.target and use JavaScript to get attribute.
Solution #1 JavaScript getAttribute
editSchool(e) {
console.log("School Id");
console.log(e.target.getAttribute('id'));
}
e.target will be the HTML Element that you click, and we can use JavaScript way to get attribute. (Please Note that, Javascript way is not React way)
But there are another way and you'll see this way more often.
Solution #2 You can define a function directly in a render
<button id={school.id} onClick={e => this.editSchool(school.id)}>
Please be careful about this another pitfall,
2nd Aha: Bind onClick to function, not result of a function.
Don't do this
<button id={school.id} onClick={this.editSchool(scholl.id)}> // This is incorrect
The thing is onClick prop expect a function to call when someone click.
The first one we define a function e => this.editSchool(school.id) and bind onClick with the newly defined function.
While the second, we just bind onClick to a "result" of function this.editSchool(school.id), which is not a function.

How to navigate to a specific users profile page after selecting him/her from a list of multiple users?

How do I code this functionality in react-native?
eg. In Instagram when you go to your followers' page, you can view a whole list. You can tap on any of them and you will navigate to that user's specific profile.
I was wondering if it has something to do with React-Navigation like passing some unique id or code, but I am still unclear, please help me out.
P.S I am using cloud firestore from firebase as my database.
The way I would do this is as follows:
1) Create a FlatList:
<FlatList
data={//list of users}
renderItem={this.renderList}
keyExtractor={(item, index) => index.toString()}
/>
2) Every element in the FlatList is a custom component. Navigation props is also passed to the component along with the data. The handler function for renderItem is given below:
renderList = ({ item }) => (
<UserSummary data={item} navigation={this.props.navigation} />
);
3) UserSummary is in fact a Touchable element (say Touchable Opacity) and the onPress event handler for that is given below:
onPress={() =>
props.navigation.navigate("UserDetailsScreen", {
userDetails: props.data
})
Note that I have also passed some data along with the navigation. Let's say, it's some userID that is unique. This information can be used in the UserDetailsScreen to render the details of the user.
Hope this will give you an idea.
you can refer this link. You can pass id as parameter as this.props.navigation.navigate('RouteName', { /* params go here */ }) .

How to attach view button to an item list

Please I am currently displaying a list of business from a businesses array. Each business has its unique id. I am displaying the businesses by mapping my business array through a react "Business Card Component" This card is a small materialize card that shows few properties of the business.
The API endpoint to get the full details of a particular businesses is < url/businesses/id >
On each business card, I have a button which says "visit", such that when a user clicks the button, he send request to url/businesses/id, and when the request is successful, I will update the state using redux and render the BusinessProfile page that will render the business particulars.
My approach is to concatenate url/businesses/ with the id of business and send the request.
But I dont know how to access the business id from the "visit" button.
const FoundBusinesses = realBusiness.map((eachBusiness, index) => {
return (
<BusinessCard key={index}
business={eachBusiness}
businessPic={profilePicture}
handleClick={this.handleClick}
/>
)
})
I will appreciate any help please
handleClick={() => {this.handleClick(business.id)}
This link is also good, it shows you how you can send your data as a parameter to your click handler. https://medium.freecodecamp.org/reactjs-pass-parameters-to-event-handlers-ca1f5c422b9
If the 'visit' button is inside BusinessCard, you should already have the id inside eachBusiness.businessId, correct? And if I am understanding your question correctly, you can pass it to your handleclick function and change the URL. The below code is using history from react-router to change the url.
With an arrow function inside the button
HandleClick:
handleClick(businessId) {
this.props.history.push(`url/businesses/${businessId}`)
}
Inside BusinessCard:
<button onClick={() => this.props.handleClick(this.props.business.businessId)}>
See business info
</button>
HandleClick will use that particular Id when it executes so it pushes to the correct URL.
With a closure
You can also do the same with a closure for cleaner function call:
handleClick(businessId) {
return () => this.props.history.push(`url/businesses/${businessId}`)
}
Inside BusinessCard:
<button onClick={this.props.handleClick(this.props.business.businessId)}>
See business info
</button>

Categories

Resources