Update on Async Rendering- ReactJs - reactjs

Following a tutorial-
Console Warning:
componentWillUpdate has been renamed, and is not recommended for use. Move data fetching code or side effects to componentDidUpdate.Rename componentWillUpdate UNSAFE_componentWillUpdate to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. Please update the following components: Identicon
At first, the app correctly displayed "Welcome Username", but after refreshing I got the warning on the console.
Now, when I type something into Username... and click on Set Nickname nothing happens.
I am expecting to see "Welcome Username"
<div className={styles.welcome}>Wecome {username}</div>
I do not think there is anything wrong with my handleSetUsername function, because it worked previously.
On the Moralis app I see that there are 4 users correctly connected from my Metamask account.
Sidebar.js
const {
isAuthenticated,
nickname,
setNickname,
username,
setUsername,
handleSetUsername,
} = useContext(AmazonContext)
return (
<div className={styles.container}>
<div className={styles.profile}>
{isAuthenticated && (
<>
<div className={styles.profilePicContainer}>
<Image
src={`https://avatars.dicebear.com/api/pixel-art/${username}.svg`}
alt='profile'
className={styles.profilePic}
height={100}
width={100}
/>
</div>
{!username ? (
<>
<div className={styles.username}>
<input
type='text'
placeholder='Username....'
className={styles.usernameInput}
value={nickname}
onChange={e => setNickname(e.target.value)}
/>
</div>
<button
className={styles.setNickname}
onClick={handleSetUsername}
>
Set Nickname
</button>
</>
) : (
<div>
<div className={styles.welcome}>Wecome {username}</div>
</div>
)}
</>
)}
<div className={styles.connectButton}>
<ConnectButton />
</div>
</div>
<div className={styles.menu}>
<Link href='/'>
<div className={styles.menuItem}>
<Image
src={logo}
height={30}
width={30}
className={styles.amazonLogo}
/>
My Amazon
<br /> Board
</div>
</Link>
<div className={styles.menuItem}>
<FaBox />
Collections
</div>
<div className={styles.menuItem}>
<BsFillBookmarkFill />
Saved
</div>
<div className={styles.menuItem}>
<BsFillPersonFill />
Profile
</div>
<Link href='/history'>
<div className={styles.menuItem}>
<AiOutlineHistory />
Transaction History
</div>
</Link>
</div>
<div className={styles.companyName}>
<Image src={logofull} alt='amazon' height={100} width={100} />
</div>
</div>
)
}
export default Sidebar

Related

Reactjs: Antd Table onRowClick trigger all event

So i'm new to reactjs, im doing a table that when you click on 1 row it will render a detail description for that row. I have some button to trigger some event on that description table. But when i'm click the row on the table the description still render but the problem is, all the event in the descroption is trigger when i click on the row table not the button. Help pls
Here is my code:
const [displayCoursesDescription, setDisplayCoursesDescription] = useState({ coursesDescription: [] });
const handleCloseCoursesDescription = () => setDisplayCoursesDescription({ coursesDescription: [] });
const handleReloadCourse = () => {
setDisplayCoursesDescription({ coursesDescription: [] });
dispatchStudentCourses();
};
<div className="studentDashboardContent">
<div className="TableHeader">
<img className="courseIcon" src={courseActive} alt="courseActive" role="presentation" />
<p className="courseText">Courses</p>
<div className="ToolBar">
<OutlinedButton
icon={<ReloadOutlined style={{ width: '32px' }} />}
color={COLOR}
backgroundColor={BACKGROUND_COLOR}
display="inline"
onClick={handleReloadCourse}
/>
<SearchBox
placeholder="Search for courses"
color={COLOR}
backgroundColor={BACKGROUND_COLOR}
display="inline" // inline || none
/>
</div>
</div>
{courses && courses.status === API_STATUS.LOADING ? (
<LoadingIndicator />
) : (
<Table
className="studentTable"
columns={columns}
dataSource={coursesSource}
pagination={{ hideOnSinglePage: true }}
onRow={(record) => ({
onClick: (event) => {
setDisplayCoursesDescription({ coursesDescription: record });
getDepartmentById(record.department);
},
})}
/>
)}
</div>
{displayCoursesDescription.coursesDescription.key ? (
<div className="CourseDescription">
<div className="HeaderButton">
<a
href={displayCoursesDescription.coursesDescription.hostname}
className="courseUrl"
rel="noreferrer"
target="_blank"
>
<div className="forwardBtn" role="presentation">
<p className="forwardText">Go to course</p>
<img className="forwardImg" src={forward} alt="forward" />
</div>
</a>
<Button className="closeBtn" type="primary" icon={<CloseOutlined />} onClick={console.log('click1')} />
</div>
<div className="courseCodeName">
<p className="courseCode">{displayCoursesDescription.coursesDescription.code}</p>
<p className="courseName">{displayCoursesDescription.coursesDescription.name}</p>
</div>
<p className="departmentTitle">DEPARTMENT</p>
<div className="courseDepartment">
<img className="departmentImg" src={departmentIcon} alt="department" />
<p className="departmentName">{departments.name}</p>
</div>
<div className="courseDescription">
<p className="descriptionTitle">COURSE DESCRIPTION</p>
<p className="description">{displayCoursesDescription.coursesDescription.description}</p>
</div>
<Button className="unassignCourse" type="primary" danger onClick={console.log('click2')}>
Exit course <LoginOutlined />
</Button>
</div>
) : (
<div className="studentBackground">
<div className="dashboardContainer">
<p className="hiText">Hi {user.name}. How are you today?</p>
<img className="dashboardIMG" src={dashboardIMG} alt="dashboardimg" />
</div>
</div>
)}
Here is the console log that 2 onClick event were trigger when i click on the table Row
enter image description here

How to use react-semantic-ui transition.group on map

I have a bunch of cards and I would like to have transition with a delay on each item but couldn't really figure it out on how to implement this.
According to the documentation I have to use something like this:
<Transition.Group
as={List}
duration={200}
divided
size='huge'
verticalAlign='middle'
>
{items.map((item) => (
<List.Item key={item}>
<Image avatar src={`/images/avatar/small/${item}.jpg`} />
<List.Content header={_.startCase(item)} />
</List.Item>
))}
</Transition.Group>
but I didn't really get what is as={List} doing there. That's why couldn't really go forward with my solution. Any help will be appreciated.
Here is what I have:
<Card.Group itemsPerRow={itemsPerRow} centered>
{data.map((e) => {
const dateToFormat = e.created_at;
const userIndex = data.indexOf(e);
return (
<Card raised>
<Image
src={readmeFiles[userIndex].image}
wrapped
size="large"
ui={false}
onClick={() => {
const index = data.indexOf(e);
clickHandler(index);
}}
/>
<Card.Content>
<Card.Header></Card.Header>
<Card.Meta>
<span className="date">{e.name}</span>
</Card.Meta>
<Card.Description>{e.description}</Card.Description>
</Card.Content>
<Card.Content extra>
<a>
<Icon name="calendar alternate outline" />
Created: <Moment date={dateToFormat} fromNow />
</a>
</Card.Content>
</Card>
);
})}
The as={List} tells semantic to render this Transition.Group component as a List component, which serves as a parent to the List.Item components. Those will only render correctly if they have a List as parent. You can check the resulting html out here.
The following snippet:
<Transition.Group
as={List}
duration={200}
divided
size='huge'
verticalAlign='middle'
>
{items.map((item) => (
<List.Item key={item}>
<Image avatar src={`/images/avatar/small/${item}.jpg`} />
<List.Content header={_.startCase(item)} />
</List.Item>
))}
</Transition.Group>
Generates the following html:
<div role="list" class="ui huge divided middle aligned list">
<div role="listitem" class="item fade visible transition">
<img src="/images/avatar/small/ade.jpg" class="ui avatar image" />
<div class="content"><div class="header">Ade</div></div>
</div>
<div role="listitem" class="item fade visible transition">
<img src="/images/avatar/small/chris.jpg" class="ui avatar image" />
<div class="content"><div class="header">Chris</div></div>
</div>
<div role="listitem" class="item fade visible transition">
<img src="/images/avatar/small/christian.jpg" class="ui avatar image" />
<div class="content"><div class="header">Christian</div></div>
</div>
</div>
As you can see the first div says role="List" and has the list css class added. In your case the parent would be the Card.Group component.

ReactjS - const loads all states before being fetched

Hey guys I am trying to pass a URL for background image into the ResultsItem component. My problem is that the state of places is not defined until data are fetched. The problem is with the const Thumbnail. I always get an error of "TypeError: Cannot read property 'photos' of undefined".
render() {
const Thumbnail = `https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=${places.photos.photoreference}&key=MYAPIKEY
`;
return (
<div>
<div className="flex align-center">
<div className="search">
<SearchInput
id="autocomplete"
placeholder="Search by address"
width="100%"
height={56}
/>
<Script
url="https://maps.googleapis.com/maps/api/js?key=MYAPIKEY&libraries=places,geometry&callback=initAutocomplete"
onLoad={this.handleScriptLoad}
/>
</div>
<div className="current-location">
<Tooltip content="Use current location">
<IconButton
icon="locate"
iconSize={16}
height={32}
onClick={this.currentLocationOnClick}
>
{this.state.lat} & {this.state.lng}
</IconButton>
</Tooltip>
</div>
</div>
<div className="results">
{this.state.places.map(places => (
<div className="results-item" onClick={this.props.sideBarOpen}>
<ResultsItem name={places.name} image={Thumbnail} />
</div>
))}
</div>
</div>
);
}
}
The fact that places is available in an async manner, the best solution is to resolve Thumbnail within the map function itself.
That way it will only be required and resolved when places is available
render() {
return (
<div>
<div className="flex align-center">
<div className="search">
<SearchInput
id="autocomplete"
placeholder="Search by address"
width="100%"
height={56}
/>
<Script
url="https://maps.googleapis.com/maps/api/js?key=MYAPIKEY&libraries=places,geometry&callback=initAutocomplete"
onLoad={this.handleScriptLoad}
/>
</div>
<div className="current-location">
<Tooltip content="Use current location">
<IconButton
icon="locate"
iconSize={16}
height={32}
onClick={this.currentLocationOnClick}
>
{this.state.lat} & {this.state.lng}
</IconButton>
</Tooltip>
</div>
</div>
<div className="results">
{this.state.places.map(places => {
const Thumbnail = `https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=${places.photos.photoreference}&key=MYAPIKEY
`;
return(
<div className="results-item" onClick={this.props.sideBarOpen}>
<ResultsItem name={places.name} image={Thumbnail} />
</div>
)})}
</div>
</div>
);
}
}
You should prevent to load data before they are actually loaded from server, so you should render a loader before use your result in this way:
if(isLoading) { // You should set the loading state before to load data from server
return <span>Loading</span>
}
return ( // This shows your data after loading goes to false
<div>Your code here</div>
)

How to build Tabs component Reactjs

I'm trying to build a Tabs component with ReactJS and I'm following a CSS stylesheet.So, I would love to have this as render :
<div data-container="" class="tabs tabs-horizontal">
<div class="tabs-header">
<div class="tabs-header-tab ph active" data-tab="0" style="transform: translateX(0px) translateZ(0px);">Personal
</div>
<div class="tabs-header-tab ph undefined" data-tab="0" style="transform: translateX(0px) translateZ(0px);">Job
</div>
<div class="tabs-header-tab ph undefined" data-tab="0" style="transform: translateX(0px) translateZ(0px);">
Salary</div>
</div>
<div data-container="" class="tabs-content">
<div data-container="" class="tabs-content-tab open" data-tab="0">
<div>I am a HR Specialist.</div>
</div>
<div data-container="" class="tabs-content-tab undefined" data-tab="0">
<div>No records have been added yet</div>
</div>
<div data-container="" class="tabs-content-tab undefined" data-tab="0">
<div>This type of information needs to be added by your manager</div>
</div>
</div>
</div>
And this is what the components looks like now :
<Tabs>
<TabHeaders>
<TabHeadersItem text="Personal" state="active" />
<TabHeadersItem text="Job" />
<TabHeadersItem text="Salary" />
</TabHeaders>
<TabContents>
<TabContentsItem
content="I am a HR Specialist."
open="open"
/>
<TabContentsItem content="No records have been added yet" />
<TabContentsItem content="This type of information needs to be added by your manager" />
</TabContents>
</Tabs>
So, I'm trying to find a solution, when user clicks on a header it becomes "active" and its content "open" while the others should be closed and not active.
Ok so since you've edited your question, I'll do with mine. The idea is the same: To keep the state of which tab is open, and since you don't want to keep your tabs in a list, then you need to link a TabHeader to a TabContent:
const TabHeaderItem = props => {
return (
<div
onClick={() => props.changeTab(props.text.toLowerCase())}
className={props.state ? "active" : ""}
>
{props.text}
</div>
);
};
const TabContentsItem = props => {
return <div className={props.open ? "open" : "closed"}>{props.content}</div>;
};
const TabComponent = () {
const [active, setActive] = useState("personal");
const changeTab = tab => {
console.log("tab", tab);
setActive(tab);
};
return (
<div className="App">
<div className="tabs">
<TabHeaderItem
changeTab={changeTab}
text="Personal"
state={active === "personal"}
/>
<TabHeaderItem
changeTab={changeTab}
text="Job"
state={active === "job"}
/>
<TabHeaderItem
changeTab={changeTab}
text="Salary"
state={active === "salary"}
/>
</div>
<div className="tabs-content">
<TabContentsItem
content="I am a HR Specialist."
open={active === "personal"}
/>
<TabContentsItem
content="No records have been added yet"
open={active === "job"}
/>
<TabContentsItem
content="This type of information needs to be added by your manager"
open={active === "salary"}
/>
</div>
</div>
);
}
You can check out the working example here: https://codesandbox.io/s/exciting-gauss-lbghq

Cannot read property 'image_url' of undefined in React

I am very new to react and I am trying to show data
but I am getting the error
No Data is appear when i add some code about image_url, title,source_url etc....
TypeError: Cannot read property 'image_url' of undefined
In Recipe.js,
import React, { Component } from 'react'
export default class Recipe extends Component {
render() {
const {
image_url,
title,
source_url,
publisher,
recipe_id
} = this.props.recipe;
return (
<React.Fragment>
<h1>Recipe</h1>
<div className="col-10 mx-auto col-md-6 col-lg-4">
<div className="card">
<img src={image_url} className="img-card-top" style={{height:"14rem"}} alt="recipe" />
<div className="card-body text-capitalize">
<h5>{title}</h5>
<h6 className="text-warning text-slanted">
provided by {publisher}
</h6>
</div>
<div className="card-footer">
<button type="button" className="btn btn-outline-primary">Details</button>
Recipe url
</div>
</div>
</div>
</React.Fragment>
);
}
}
In ReactList.js,
<div className="row">
{recipes.map (recipe => {
return <Recipe key={recipe.recipe_id} recipe={recipe}
/>;
})}
</div>
</div>
<Recipe />
</React.Fragment>
error occur as you use two time <Recipe /> in RecipeList.js,
Removed one <Recipe />,
error will solve
Change
<div className="row">
{recipes.map (recipe => {
return <Recipe key={recipe.recipe_id} recipe={recipe}
/>;
})}
</div>
</div>
<Recipe />
</React.Fragment>
To
<div className="row">
{recipes.map (recipe => {
return <Recipe key={recipe.recipe_id} recipe={recipe}
/>;
})}
</div>
</div>
</React.Fragment>

Resources