Radio Button clicked value get the previous clicked value React - reactjs

I have MUI radio buttons which I use to get filter criteria and I filter an object. Then i render the filtered object in an owl carousal to show. But when I click on a radio button it always takes the previously clicked value of the radio button. I have used ternary conditions to check but it keeps happening I couldb't figure out following is my code.
<FormControl>
<RadioGroup
row
aria-labelledby="demo-row-radio-buttons-group-label"
name="row-radio-buttons-group"
value={movieType}
onChange={movieTypeChange}
>
<FormControlLabel
value="1"
control={<Radio color="error" />}
label="All"
/>
<FormControlLabel
value="2"
control={<Radio color="error" />}
label="Now Showing"
/>
<FormControlLabel
value="3"
control={<Radio color="error" />}
label="Upcoming"
/>
</RadioGroup>
</FormControl>
{filterdMovie.length > 0 ? (
<OwlCarousel
className="owl-theme"
loop={movieCount}
center={movieCount}
margin={1}
autoplay={true}
dots={false}
items={3}
touchDrag={true}
lazyLoad={true}
responsive={state.responsive}
// responsive={"0:{items:1,},600:{items:3,},1000:{items:5,}"}
animateOut={"fadeOut"}
>
{filterdMovie.map((movieBannertop, idx) => {
return (
<div key={idx}>
<div className="item">
<div className="prs_upcom_movie_box_wrapper">
<div className="prs_upcom_movie_img_box">
<img
src={
movieBannertop.thumbnail
// HTMLImageElement.complete
// ?
// `${process.env.REACT_APP_DEV_BASE_URL_IMAGE}/movie/${movieBannertop.id}/thumbnail.jpg`
// : placeholder
}
alt="movie_img"
/>
<div className="prs_upcom_movie_img_overlay"></div>
<div className="prs_upcom_movie_img_btn_wrapper">
<ul>
<li>
{movieBannertop.bookingOpen ? (
<a
href
onClick={() => viewMovie(movieBannertop)}
style={{ textDecoration: "none" }}
>
More Info
</a>
) : null}
</li>
<li>
{!movieBannertop.upcoming ? (
<a
href
onClick={() => viewMovie(movieBannertop)}
style={{ textDecoration: "none" }}
>
Now Showing
</a>
) : (
<a
href
style={{
textDecoration: "none",
backgroundColor: "#2488ed",
}}
onClick={() => viewMovie(movieBannertop)}
>
Coming Soon
</a>
)}
</li>
</ul>
</div>
</div>
<div className="prs_upcom_movie_content_box">
<div className="prs_upcom_movie_content_box_inner">
<Tooltip title={movieBannertop.name}>
<h2>
<a
href
onClick={() => viewMovie(movieBannertop)}
style={{ textDecoration: "none" }}
>
{" "}
{movieBannertop.name.length > 10
? `${movieBannertop.name.substring(0, 10)}...`
: movieBannertop.name}
</a>
</h2>
</Tooltip>
<p>{movieBannertop.genre}</p>
</div>
<div className="prs_upcom_movie_content_box_inner_icon">
{/* <ul>
<li>
<a href="movie_booking.html">
<i className="flaticon-cart-of-ecommerce"></i>
</a>
</li>
</ul> */}
</div>
</div>
</div>
</div>
</div>
);
})}
</OwlCarousel>
) : (
<>
<Stack
direction="column"
justifyContent="center"
alignItems="center"
>
<img src={notFound} alt="" width="50%" />
<h4>No Movies Found</h4>
</Stack>
</>
)}
const movieTypeChange = (e) => {
e.preventDefault();
setMovieType(e.target.value);
const value = e.target.value;
if (value === "1") {
setFileredMovies(onlineMovies);
}
if (value === "2") {
let shows = [];
onlineMovies.forEach((element) => {
if (!element.upcoming) {
shows.push(element);
}
});
setFileredMovies(shows);
console.log(shows);
}
if (value === "3") {
console.log("3");
let shows = [];
onlineMovies.forEach((element) => {
if (element.upcoming) {
shows.push(element);
}
});
setFileredMovies(shows);
}
};

const movieTypeChange = (e) => {
var shows = [];
const value = e.target.value;
if (value === "1") {
setFileredMovies(onlineMovies);
}
if (value === "2") {
onlineMovies.forEach((element) => {
if (!element.upcoming) {
shows.push(element);
}
});
setFileredMovies(shows);
}
if (value === "3") {
onlineMovies.forEach((element) => {
if (element.upcoming) {
shows.push(element);
}
});
setFileredMovies(shows);
}
setMovieType(value);
};

Related

is there a way to display each individual comment data without it being set to the recently clicked comment?

im currently building a website similar to reddit but im having troubles with the comments, i can toggle the comment on and off on click but whenever more than one comment is clicked it just displays the comment data of the recent comment that was clicked.
this is my code:
const handleComments = (subText, id) => {
setCommentIds(prev => (prev.includes(id) ? prev.filter(cid => cid !== id) : [...prev, id]));
dispatch(getComments({ subText, id }));
};
const popularRendering = () => {
if (popular.isLoading) {
return Array(5)
.fill()
.map((_, index) => <FeedSkeleton key={index} />);
} else if (popular.data && popular.data.data) {
return popular.data.data.children.map((data, index) => (
<div className="box-container" key={index}>
<div className="data-container">
<div className="votes-container">
<TiArrowUpOutline
size={27}
className={`${upvoted[data.data.id] ? "up-voted" : "up-vote"}`}
onClick={() => handleUpVote(data.data.id)}
/>
<p className={upvoted[data.data.id] ? "up-voted" : downvoted[data.data.id] ? "down-voted" : ""}>{formatNumber(data.data.score)}</p>
<TiArrowDownOutline
size={27}
className={`${downvoted[data.data.id] ? "down-voted" : "down-vote"}`}
onClick={() => handleDownVote(data.data.id)}
/>
</div>
<div className="feed-header">
{subredditIconUrl[data.data.subreddit_name_prefixed] ? (
<img className="feed-icon-img" src={subredditIconUrl[data.data.subreddit_name_prefixed]} alt="subreddit-icon" />
) : null}
<p>{data.data.subreddit_name_prefixed}</p>
<span>Posted by u/{data.data.author} </span>
<span>{formatDate(data.data.created_utc)}</span>
</div>
<div className="feed-body">
<p>{data.data.title}</p>
{isImage(data.data.url) ? (
<img src={data.data.url} alt="subreddit" />
) : data.data.is_video ? (
<video height="auto" width="100%" controls>
<source src={data.data.media.reddit_video.fallback_url} />
<p className="error-media">Sorry, this content cannot be displayed.</p>
</video>
) : null}
</div>
<div className="footer">
<div className="comments" onClick={() => handleComments(data.data.subreddit_name_prefixed, data.data.id)}>
<GoComment size={25} className="comment-icon" />
<p>{formatNumber(data.data.num_comments)} Comments</p>
</div>
</div>
{subreddit.commentsLoading
? Array(5)
.fill()
.map((_, index) => <CommentsSkeleton key={index} />)
: commentIds.includes(data.data.id) && <Comments postId={data.data.id} />}
</div>
</div>
));
}
};
i tried using an array to store the ids and only display the ids of those comments but it just always resulted in issues and an infinite loop of headaches and errors.

How to change text-overflow on Blueprintjs Suggest component in React?

I have a Suggest component that is rendered out like this:
<div class="bp4-popover-content">
<div>
<ul class="b4-menu">
<li>
<a>
<div class="bp4-fill bp4-text-overflow-ellipsis">
<div>Some text</div>
</div>
</a>
</li>
</ul>
</div>
</div>
By default, it uses text-overflow ellipsis, but i want to switch it to bp4-text-overflow-wrap. How can I achieve this in React? What I have so far:
const ItemSelect = Suggest.ofType<Items>();
<ItemSelect
fill
items={newUserItems}
itemListPredicate={filterItems}
itemRenderer={renderItem}
noResults={<MenuItem disabled={true} text="No results." />}
onItemSelect={(item, event) => {
setQuery(item.name);
item.isNew = false;
onItemSelect(item);
}}
popoverProps={{
minimal: true,
popoverClassName: `custom-class ${
isOpenLine ? "open-line-popover" : "non-open-line-popover"
}`,
}}
inputValueRenderer={() => query}
resetOnSelect={true}
resetOnQuery={true}
onQueryChange={(q, event) => {
if (event === undefined) {
setQuery(q);
}
}}
query={query}
inputProps={{ inputRef: inputRef }}
/>

How can I have conditional buttons without repeating code. React

I am trying to make it so the buttons are only visible in my create page. I have figured out how to do this although in such a way that code is repeated
if (mode != "view") {
return (
<>
<section
className={`col-md-${sectionInputArray.width} justify-content border-end mt-2 mb-2`}
>
<h4 className="border-bottom">{`${sectionInputArray.name}`} </h4>
<div className="col-12"></div>
{sectionInputArray.contents.map((input, i) => (
<NestedDynamicInputCreation
singleInput={input}
formData={formData}
setFormData={setFormData}
options={options}
mode={mode}
staticVars={staticVars}
SetStaticVars={SetStaticVars}
i={i}
idx={idx}
arrayLength={arrayLength}
sectionUID={sectionInputArray.UID}
/>
))}
{/* Button to add new field */}
<button
id ="TestButton1"
className="btn btn-primary bt-btn m-3"
type="button"
onClick={() => {
// console.log(`${sectionInputArray.name} section will be added`);
// console.log({ formDataTarget: formData[sectionInputArray.UID] });
// New Inbound Rule
// console.log([
// ...formData[sectionInputArray.UID],
// NestedListIDSingle(sectionInputArray),
// ]);
let addedFormData = {
...formData,
[`${sectionInputArray.UID}`]: [
...formData[sectionInputArray.UID],
NestedListIDSingle(sectionInputArray),
],
};
let randomVal = Math.random()
.toString(36)
// .replace(/[^a-z]+/g, "")
.substr(0, 11);
let withRandom = {
...addedFormData,
rand_value: randomVal,
};
// console.log({ addedFormData: addedFormData });
setFormData(withRandom);
}}
>
Add New {sectionInputArray.name}
</button>
{/* Button to remove section (or created form) */}
<button
className="btn btn-primary bt-btn m-3"
type="button"
onClick={() => {
console.log(
`${sectionInputArray.name}-${idx} section will be removed`
);
// formData[sectionInputArray.UID].splice(idx, 1);
let formDataTarget = formData[sectionInputArray.UID];
// console.log(formDataTarget);
let newFD = formData;
newFD[sectionInputArray.UID].splice(idx, 1);
let randomVal = Math.random()
.toString(36)
// .replace(/[^a-z]+/g, "")
.substr(0, 11);
let withRandom = {
...newFD,
rand_value: randomVal,
};
setFormData(withRandom);
}}
>
Remove {sectionInputArray.name}
</button>
</section>
</>
);
} else {
return (
<>
<section
className={`col-md-${sectionInputArray.width} justify-content border-end mt-2 mb-2`}
>
<h4 className="border-bottom">{`${sectionInputArray.name}`} </h4>
<div className="col-12"></div>
{sectionInputArray.contents.map((input, i) => (
<NestedDynamicInputCreation
singleInput={input}
formData={formData}
setFormData={setFormData}
options={options}
mode={mode}
staticVars={staticVars}
SetStaticVars={SetStaticVars}
i={i}
idx={idx}
arrayLength={arrayLength}
sectionUID={sectionInputArray.UID}
/>
))}
</section>
</>
)
As you can see above when it is not on the view page it will then not use the buttons as it is removed within the 'else' section.
How could i create an instance of this, when the button is conditional. I tried placing an if statement just before the button section however that did not work
Yes you can do it - place your conditional rendering (operator &&) after your <NestedDynamicInputCreation
return (
<>
<section
className={`col-md-${sectionInputArray.width} justify-content border-end mt-2 mb-2`}
>
<h4 className="border-bottom">{`${sectionInputArray.name}`} </h4>
<div className="col-12"></div>
{sectionInputArray.contents.map((input, i) => (
<NestedDynamicInputCreation
singleInput={input}
formData={formData}
setFormData={setFormData}
options={options}
mode={mode}
staticVars={staticVars}
SetStaticVars={SetStaticVars}
i={i}
idx={idx}
arrayLength={arrayLength}
sectionUID={sectionInputArray.UID}
/>
))}
{mode != 'view' && (
<>
<button
id ="TestButton1"
className="btn btn-primary bt-btn m-3"
type="button"
onClick={() => {
...
})
>
Add New {sectionInputArray.name}
</button>
<button
className="btn btn-primary bt-btn m-3"
type="button"
onClick={() => {
..
})
>
Remove {sectionInputArray.name}
</button>
</>
)}
</section>
</>
);
If the content the same you could use Fragments and conditionally show the buttons:
return (
<>
<section
className={`col-md-${sectionInputArray.width} justify-content border-end mt-2 mb-2`}
>
<h4 className="border-bottom">{`${sectionInputArray.name}`} </h4>
<div className="col-12"></div>
{sectionInputArray.contents.map((input, i) => (
<NestedDynamicInputCreation
singleInput={input}
formData={formData}
setFormData={setFormData}
options={options}
mode={mode}
staticVars={staticVars}
SetStaticVars={SetStaticVars}
i={i}
idx={idx}
arrayLength={arrayLength}
sectionUID={sectionInputArray.UID}
/>
))}
{mode !== 'view' && (
<>
<button
id ="TestButton1"
className="btn btn-primary bt-btn m-3"
type="button"
onClick={() => {
// console.log(`${sectionInputArray.name} section will be added`);
// console.log({ formDataTarget: formData[sectionInputArray.UID] });
// New Inbound Rule
// console.log([
// ...formData[sectionInputArray.UID],
// NestedListIDSingle(sectionInputArray),
// ]);
let addedFormData = {
...formData,
[`${sectionInputArray.UID}`]: [
...formData[sectionInputArray.UID],
NestedListIDSingle(sectionInputArray),
],
};
let randomVal = Math.random()
.toString(36)
// .replace(/[^a-z]+/g, "")
.substr(0, 11);
let withRandom = {
...addedFormData,
rand_value: randomVal,
};
// console.log({ addedFormData: addedFormData });
setFormData(withRandom);
}}
>
Add New {sectionInputArray.name}
</button>
{/* Button to remove section (or created form) */}
<button
className="btn btn-primary bt-btn m-3"
type="button"
onClick={() => {
console.log(
`${sectionInputArray.name}-${idx} section will be removed`
);
// formData[sectionInputArray.UID].splice(idx, 1);
let formDataTarget = formData[sectionInputArray.UID];
// console.log(formDataTarget);
let newFD = formData;
newFD[sectionInputArray.UID].splice(idx, 1);
let randomVal = Math.random()
.toString(36)
// .replace(/[^a-z]+/g, "")
.substr(0, 11);
let withRandom = {
...newFD,
rand_value: randomVal,
};
setFormData(withRandom);
}}
>
Remove {sectionInputArray.name}
</button>
</>
)}
</section>
</>
);

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

findDOMNode is deprecated in StrictMode, Reactjs Modal Component

Reactjs shows this error when i open modal that is from another component
"index.js:1 Warning: findDOMNode is deprecated in StrictMode. findDOMNode was passed an instance of Modal which is inside StrictMode. Instead, add a ref directly to the element you want to reference."
I've tried alot of other solutions but none of them work in my case
my code file:
class Routes extends Component {
componentDidMount() {
console.log('Component did mount!')
}
loginModalRef = ({ handleShow }) => {
this.showModal = handleShow;
}
onLoginClick = () => {
this.showModal();
}
ShopersModalRef = ({ handleShoperShow }) => {
this.showShoperModal = handleShoperShow;
}
onShopersClick = () => {
this.showShoperModal();
}
//ChargeModalRef = ({ handleChargeShow }) => {
// this.showChargeModal = handleChargeShow;
//}
// onChargeClick = () => {
// this.showChargeModal();
// }
render() {
return (
<div>
{/*<chargeFeeModal ref={this.ChargeModalRef}></chargeFeeModal>*/}
<FormModal ref={this.loginModalRef}></FormModal>
<ShopersModal ref={this.ShopersModalRef}></ShopersModal>
<AppBar position="sticky" className="appbar">
<Toolbar className="NavbarTop">
<div className='row w-100'>
<div className="col-4 LogoOrBack">
<section className="leftBox shopname ml-4">
<Typography className="typography">
{Text}
</Typography>
</section>
</div>
<div className="col-4 centered">
<section className="centerBox">
<Typography className="typography">
<b>Stores</b>
</Typography>
</section>
</div>
<div className="col-4 righted">
<section className="rightBox">
<Typography className="typography">
<Button className="primary btn AccountBtn" onClick={this.onLoginClick}>
<img alt="user account avatar" src={require('../../../assets/images/placeholder_account.png')} className="buttonImage" /> Account
</Button>
<Button className="primary btn" onClick={this.onLoginClick}>
<i className="fa fa-cart-plus cart"></i>
</Button>
</Typography>
</section>
</div>
</div>
</Toolbar>
<Toolbar>
<div className='row w-100'>
<div className='col-lg-4'>
{(() => {
//Javascript for changing buttons
switch (history.location.pathname) {
case "/": return <Button onClick={this.onLoginClick} className="primary postalCodeBtn" >
<img alt="home icon" src={require('../../../assets/images/homeicon.png')} className="buttonImage" /> <b>M4b 146, CA</b> <i className="fa fa-chevron-down downIco"></i>
</Button>;
default: return (
<Button onClick={this.onShopersClick} className="primary postalCodeBtn" >
<img alt="home icon" src={require('../../../assets/images/time.png')} className="buttonImage" /> <b style={{ textTransform: 'capitalize' }}>Shoppers Occupied</b>
</Button>
);
}
})()}
</div>
<div className="col-lg-4 centered p-1 pl-4" >
<div className="searchContainer">
<i className="fa fa-search searchIcon"></i>
<input className="searchBox" type="search" name="search" placeholder="Search Stores" />
</div>
</div>
{TabsShowOrNo}
</div>
</Toolbar>
</AppBar>
<AnimatedSwitch
atEnter={{ opacity: 0 }}
atLeave={{ opacity: 0 }}
atActive={{ opacity: 1 }}
className="switch-wrapper"
>
<Route exact path="/" component={HomePage} />
<Route path='/store/orders/' component={OrdersPage} />
<Route path='/store/aisles/' component={AislesPage} />
<Route path="/store/featured" component={SingleStorePage} />
<Route component={NotFound} />
</AnimatedSwitch>
</div >
)
}
}```
any help will be appreciate

Resources