Edit button + populate field with redux / react - javascript

I need send the data line from DataTable to another page and populate the fields with React or Redux... how can i do that?
class Dtable extends Component {
componentWillMount() {
this.props.getList();
}
actionTemplate(rowData, column) {
return <div>
<Button type="button" icon="fa-search" className="ui-button-success"></Button>
<Button type="submit" icon="fa-edit" onClick={console.log(column)} className="ui-button-warning" ></Button>
</div>
}
render() {
return (
<div>
<Form onSubmit={this.props.create} />
<div className="content-section implementation" style={{ paddingTop: 1 + '%' }}>
<DataTable key="idPessoa" value={this.props.list} paginator={true} paginator={true} rows={10} rowsPerPageOptions={[5, 10, 20]} >
<Column field="idPessoa" header="Propriedade" style={{ width: 5 + '%' }} />
<Column field="nome" header="Propriedade" />
<Column field="email" header="Propriedade" />
<Column field="latitude" header="Relatório" style={{ width: 15 + '%' }} />
<Column field="longitude" header="Ativo" style={{ width: 5 + '%' }} />
<Column header="Opções" body={this.actionTemplate} style={{ textAlign: 'center', width: '100px' }} />
</DataTable>
</div>
</div>
)
}
}
const mapStateToProps = state => ({ list: state.upload.list })
const mapDispatchToProps = dispatch => bindActionCreators({ getList, create, showUpdate }, dispatch)
export default connect(mapStateToProps, mapDispatchToProps)(Dtable)

I just add the arrow function on my event ..this solve my problem..thanks guys.
actionTemplate = (rowData, column) => {
return <div>
<Button type="button" icon="fa-search" imediate='true' onClick={() => this.teste(rowData.nome,rowData.email)} className="ui-button-success"></Button>
<Button type="button" icon="fa-edit" imediate='true'
onClick={() => console.log(rowData)} className="ui-button-warning" ></Button>
</div>
}
teste = (nome,mail) => {
console.log(nome)
this.setState({name:nome,email:mail})
}

Related

Load a react component on button onClick

I have the following code for a button in my ReactApp to open a new window with specific size:
<button
type="button"
style={{ height: '20px', width: '50px' }}
className="btn btn-primary"
onClick={() => {
window.open(
"",
"Popup",
"width=975, height=92, top=30"
);
}}
/>
I want to load another component when user clicks on the button. How can I achieve that? I have tried to load the component and then use it like the following, but didn't work:
import component from "./component"
<button
type="button"
style={{ height: '20px', width: '50px' }}
className="btn btn-primary"
onClick={() => {
window.open(
"{<component />}",
"Popup",
"width=975, height=92, top=30"
);
}}
/>
What would be the best way to do this?
Here is my component:
export default function component(props) {
return (
<div className="container">
<div className="cabinet"><img src={image} />
<div className="devices"> <img src={image2} />
</div>
</div>
);
}
Add a state in main page and pass it to component
const [open, setOpen] = useState[false];
const onClickHandle = () => {
setOpen(true);
};
return (
<>
<button
type="button"
style={{ height: '20px', width: '50px' }}
className="btn btn-primary"
onClick={onClickHandle}
/>
<component open={open} />
</>
);
Add a new props to control the component
export default function component(props) {
const { open } = props;
return (
<>
{open && (
<div className="container">
<div className="cabinet">
<img src={image} />
<div className="devices">
{' '}
<img src={image2} />
</div>
</div>
</div>
)}
</>
);
}
Using state hooks and conditional rendering, you can load a react component on a button onClick.
const [visible, setVisible] = React.useState(false);
function click(e) {
e.preventDefault();
setVisible(true);
}
return (
<div>
<button onClick={(event) => {
click(event)
}} />
{isVisible && (
<YourComponent />
)
}
</div>
)

Select only a card at a time on click in reactjs

I have a react component which has some cards, When I click the plus icon in the card, it would expand and show some data for 30sec and then the data will disappear and on click it will reappear again, here is the component
import React from "react";
import { FaPlus } from "react-icons/fa";
import useTimeout from "../../../common/useTimeout";
import { Modal } from "../../../common/Modal";
import { ToggleState } from "../../../common/Toggle";
import { BsSearch } from "react-icons/bs";
import AdvancedFilter from "./AdvancedFilter";
export default function CitiesList({ cities }: { cities: any }): JSX.Element {
const [filter, setFilter] = React.useState("");
const [sortType, setSortType] = React.useState("");
const [selectedCity, setSelectedCity] = React.useState<any | null>(null);
console.log(filter);
const sorted = cities.sort((a: { name: string }, b: { name: any }) => {
const isReversed = sortType === "asc" ? 1 : -1;
return isReversed * a.name.localeCompare(b.name);
});
const onSort = (sortType: React.SetStateAction<string>) => {
console.log("changed");
setSortType(sortType);
};
const [showMeta, setShowMeta] = React.useState(false);
const handleClick = () => setShowMeta(true);
const getSelectedCity = (selectedCity: any) => {
setSelectedCity(selectedCity);
console.log("SELECTED CITY", selectedCity);
};
const [visible, setVisible] = React.useState(true);
const hide = () => setVisible(false);
useTimeout(hide, 30000);
console.log("CITIES", cities);
console.log({ selectedCity });
return (
<div style={{ marginTop: "3rem" }}>
<div
style={{
display: "flex",
justifyContent: "space-between",
alignItems: "center",
marginBottom: "20px",
}}
>
<div>List of cities</div>
<div style={{ display: "flex", alignItems: "center" }}>
<div style={{ marginRight: "1rem" }}>
<ToggleState
render={({ isOpen, open, close }) => {
return (
<>
<button
type="button"
className="btn btn-primary"
onClick={() => {
isOpen ? close() : open();
}}
>
Advanced Filter
</button>
<Modal
isActive={isOpen}
modalContentWidth={"30%"}
header={() => "Advanced Filter"}
close={() => close()}
renderBody={() => {
return <AdvancedFilter close={() => close()} />;
}}
></Modal>
</>
);
}}
/>
</div>
<div style={{ position: "relative", marginRight: "1rem" }}>
<input
type="text"
placeholder="Filter"
name="namePrefix"
style={{ padding: "0.35rem" }}
onChange={(e: any) => {
setFilter(e.target.value);
}}
/>
<div style={{ position: "absolute", top: "5px", right: "5px" }}>
<BsSearch size="16" />
</div>
</div>
<div style={{ width: "8rem" }}>
<div className="btn-group">
<button
type="button"
className="btn dropdown-toggle sort-button"
data-bs-toggle="dropdown"
aria-expanded="false"
>
{sortType === "asc"
? "Ascending"
: sortType === "desc"
? "Descending"
: "Select"}
</button>
<ul className="dropdown-menu sort-button">
<li>
<button
className="dropdown-item"
type="button"
onClick={() => onSort("asc")}
>
Ascending
</button>
</li>
<li>
<button
className="dropdown-item"
type="button"
onClick={() => onSort("desc")}
>
Descending
</button>
</li>
</ul>
</div>
</div>
</div>
</div>
<div>
<div>
<div className="row">
{cities &&
sorted.map((item: any, index: number) => (
<div className="col-lg-3" key={index}>
<div
className="card"
style={{
textAlign: "center",
display: "flex",
justifyContent: "center",
paddingBottom: "1rem",
marginBottom: "1rem",
marginRight: "1rem",
}}
>
<div className="card-body">
<h5 className="card-title">{item.name}</h5>
</div>
{visible && showMeta ? (
<div>
<p>Longitude: {item.longitude}</p>
<p>Latitude: {item.latitude}</p>
<p>Population: {item.population}</p>
{/* <p>Time Zone: America</p> */}
</div>
) : (
<div
onClick={() => {
handleClick();
getSelectedCity(item.id);
}}
style={{ cursor: "pointer" }}
>
<FaPlus size="18" />
</div>
)}
</div>
</div>
))}
</div>
</div>
</div>
<div
style={{ marginTop: "30px", display: "flex", justifyContent: "center" }}
>
{cities && cities.length > 10 ? (
<button className="secondary-button">Load More</button>
) : (
<p>There are no more cities</p>
)}
</div>
</div>
);
}
here is the useTimeout function
import { useEffect, useRef } from "react";
function useTimeout(callback: () => void, delay: number | null) {
const savedCallback = useRef(callback);
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
useEffect(() => {
if (delay === null) {
return;
}
const id = setTimeout(() => savedCallback.current(), delay);
return () => clearTimeout(id);
}, [delay]);
}
export default useTimeout;
Now currently if I click on one card, all the cards opens and also after when the data disappears after 30sec it does not reappear on button click. I need to reload the page to do reappear data again.I need to solve 2 issues here: 1. how can I open one card only at a time on clicking on the icon, 2. how can I reappear data on button click without refreshing the page.
As I understand you, some information is
<p>Longitude: {item.longitude}</p>
<p>Latitude: {item.latitude}</p>
<p>Population: {item.population}</p>
You have global statement of showing this info for all cards. To reduce it, make new component which will have local state of this info:
import React from 'react'
const timeout = 15000
export const CityCard = ({item, visible, getSelectedCity}) => {
const [showMeta, setShowMeta] = React.useState(false)
const handleClick = React.useCallback(()=>{
setShowMeta(true)
setTimeout(()=>{
setShowMeta(false)
},timeout )
}, [showMeta])
return(
<div className="col-lg-3" key={index}>
<div
className="card"
style={{
textAlign: "center",
display: "flex",
justifyContent: "center",
paddingBottom: "1rem",
marginBottom: "1rem",
marginRight: "1rem",
}}
>
<div className="card-body">
<h5 className="card-title">{item.name}</h5>
</div>
{visible && showMeta ? (
<div>
<p>Longitude: {item.longitude}</p>
<p>Latitude: {item.latitude}</p>
<p>Population: {item.population}</p>
{/* <p>Time Zone: America</p> */}
</div>
) : (
<button
onClick={() => {
handleClick();
getSelectedCity(item.id);
}}
type='button'
disabled={showMeta}
style={{ cursor: "pointer" }}
>
<FaPlus size="18" />
</button>
)}
</div>
</div>
)
}
At the end, add this component to the CityList

Using Constructor(props) without Class Component

I have created a search bar in TypeScript but for now I am unable to type anything into it. All the control component tutorials that I have seen suggest to use constructor(props) or so. If I use it in my code, I get errors.
Is there any way to use it without having a class component?
For instance, I am using a const() for my page. Is there any way I can make the search bar of this functional?
const userSearchPage = () => (
<div>
<PermanentDrawerLeft></PermanentDrawerLeft>
<div className='main-content'>
<MuiThemeProvider>
<DropDownMenu >
<MenuItem style={{ fontSize: "20px" }} primaryText="Search By" />
<MenuItem value={1} style={{ fontSize: "20px" }} primaryText="First Name" />
<MenuItem value={1} style={{ fontSize: "20px" }} primaryText="Last Name" />
</DropDownMenu>
</MuiThemeProvider>
<SearchBar
onChange={() => console.log('onChange')}
onRequestSearch={() => console.log('onRequestSearch')}
style={{
margin: '0 auto',
maxWidth: 800
}}
/>
</div>
</div>
);
You must use the useState hook in a functional component.
const userSearchPage = () => {
const [value, setValue] = React.useState('');
return (
<div>
<PermanentDrawerLeft></PermanentDrawerLeft>
<div className='main-content'>
<MuiThemeProvider>
<DropDownMenu >
<MenuItem style={{ fontSize: "20px" }} primaryText="Search By" />
<MenuItem value={1} style={{ fontSize: "20px" }} primaryText="First Name" />
<MenuItem value={1} style={{ fontSize: "20px" }} primaryText="Last Name" />
</DropDownMenu>
</MuiThemeProvider>
<SearchBar
onChange={(value) => setValue(value) }
value={value}
onRequestSearch={() => console.log('onRequestSearch')}
style={{
margin: '0 auto',
maxWidth: 800
}}
/>
</div>
</div>
)} ;
Props in functional component's are simply parameters!
function SearchBar (props) {
let searchbartext = document.getElementById('searchbartext')
searchbartext.addEventListener('change', (e) => {
props.onChange(e)
}
return (
<form onsubmit={(e) => props.onRequestChange(e)}>
<input id="searchbartext" style={props.style} />
</form>
)
}
const UserSearchPage = () => {
function onRequestSearch (e) {
console.log.('request search', e)
}
function onChange(e) {
console.log('onChange')
}
return (
{SearchBar({
onChange:onChange,
onRequestSearch:onRequestSearch,
style:{
margin: '0 auto',
maxWidth: 800
}
})}
)
}
Edit: you also have to call functional component's as functions, not with <> syntax like class components. I used the term "props" inside SearchBar(props) but it's just following Reacts naming convention. You could just as easily replace it with SearchBar(bananas).

Re-render the same component with different parameter

I am working on a react project with similar functionality to a social media site. I have a user profile component below that has links to other user profiles(towards bottom of code below) that are being followed by the current user. Essentially what I am trying to do is re-render the same component with a different user. However, the link to the new user profile doesn't result in the getProfile action getting called so the redux state doesn't update. How can I navigate to the new profile and have the useEffect hook get called again with the new username?
Thank You!
import React, { useEffect, useState } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { Link } from "react-router-dom";
import GalleryItem from "../gallery-item/gallery-item.component";
import {
getProfile,
addFollow,
removeFollow
} from "../../redux/profile/profile.actions";
import { FontAwesomeIcon } from "#fortawesome/react-fontawesome";
import { faSpinner, faUserEdit } from "#fortawesome/free-solid-svg-icons";
const Profile = ({
getProfile,
addFollow,
removeFollow,
auth,
profile: { userProfile, loading },
props
}) => {
const userAlias = props.match.params.alias;
useEffect(() => {
getProfile(userAlias);
}, [getProfile]);
return loading ? (
<div class="d-flex justify-content-center">
<FontAwesomeIcon
icon={faSpinner}
className="fa-spin"
style={{ height: "50px", width: "50px", color: "white" }}
/>
</div>
) : (
<div className="container ">
<div className="row">
<div className="col-md-12 align-self-center">
<img
className="rounded-circle float-left shadow-lg"
alt="100x100"
src={userProfile.userProfileImage}
data-holder-rendered="true"
style={{ height: "200px", width: "200px" }}
/>
<div
className="vertical-center"
style={{ marginLeft: "260px", marginTop: "50px" }}
>
<h2>
{auth.user === null || auth.user.alias !== userAlias ? (
<b style={{ color: "white" }}>{userAlias}</b>
) : auth.user.alias === userAlias ? (
<b style={{ color: "white" }}>
{userAlias}
<Link className="" to="/profile/edit">
<FontAwesomeIcon
icon={faUserEdit}
className="fontAwesome"
style={{ paddingLeft: "10px", color: "limegreen" }}
/>
</Link>
</b>
) : (
<b>{userAlias}</b>
)}
</h2>
<p>
<b style={{ color: "white" }}>
{" "}
{userProfile.posts.length} Posts
</b>
<b style={{ color: "white" }}>
{" "}
{userProfile.followers.length} Followers{" "}
</b>
<b style={{ color: "white" }}>
{" "}
{userProfile.following.length} Following{" "}
</b>
</p>
{auth.user === null || auth.user.alias === userAlias ? null : auth
.user.alias !== userAlias &&
userProfile.followers.some(
e => e.userAlias === auth.user.alias
) ? (
<button
type="button"
className="btn btn-primary btn-lg "
onClick={e => removeFollow(userProfile.userId)}
>
Following
</button>
) : auth.user.alias !== userAlias ? (
<button
type="button"
className="btn btn-primary btn-lg "
onClick={e => addFollow(userProfile.userId)}
>
Not Following
</button>
) : (
<button
type="button"
className="btn btn-primary btn-lg "
disabled
>
Follow/Unfollow
</button>
)}
</div>
</div>
</div>
<hr />
<div className="row d-flex justify-content-center">
{userProfile.posts.map((post, i) => (
<GalleryItem key={i} post={post} />
))}
</div>
{userProfile.following.length > 0 ? (
<div>
<h1 className="text-white text-center mt-5">Following</h1>
<hr />
**<div className="row justify-content-center text-center px-auto">
{userProfile.following.map((profile, i) => (
<Link className="" to={`/profile/${profile.userAlias}`}>
<img
className="rounded-circle border border-info m-4"
alt="100x100"
src={profile.getFollowingUserProfileImageUrl}
data-holder-rendered="true"
style={{ height: "80px", width: "80px" }}
/>
<div
className="vertical-center"
style={{ marginBottom: "20px", color: "black" }}
>
<h5>{profile.userAlias}</h5>
</div>
</Link>
))}
</div>**
</div>
) :(<div></div>)}
</div>
);
};
Profile.propTypes = {
getProfile: PropTypes.func.isRequired,
profile: PropTypes.object.isRequired,
auth: PropTypes.object.isRequired,
props: PropTypes.object.isRequired
};
const mapStateToProps = (state, ownProps) => ({
auth: state.auth,
profile: state.profile,
props: ownProps
});
export default connect(
mapStateToProps,
{ getProfile, addFollow, removeFollow }
)(Profile);
You need to track userAlias in the useEffect's dependencies list, the api callback will be called each time it changes.
const userAlias = props.match.params.alias;
useEffect(() => {
getProfile(userAlias);
}, [getProfile, userAlias]);

Button in Prime React Table not working

I'm using prime react to create a table, the last column of the table is for the actions that can be performed on the table, however I'm following the docs, but the onClick event is not working on the buttons. When I click on the search button I get the error: "UserList.js:19 Uncaught TypeError: _this2.selectUser is not a function"
Any clues please?
The code:
actionTemplate(rowData, column) {
console.log('column', column);
console.log('rowData', rowData);
return (<div>
<Button
type="button" icon="fa-search"
className="ui-button-success" onClick={() => this.selectUser(1)}
/>
<Button
type="button" icon="fa-edit"
className="ui-button-warning"
/>
</div>);
}
selectUser(userId) {
console.log('selectUser');
userId = 1;
this.props.actions.fetchUser(userId);
}
renderTable() {
const paginatorLeft = <Button icon="fa-refresh" />;
/* const users = [
{ name: '1', email: '1981', updateDate: '', creationDate: '05/03/2016' },
{ name: '2', email: '1982', updateDate: '', creationDate: '04/02/2017' },
]; */
const { users } = this.props;
return (
<DataTable
value={users} paginator paginatorLeft={paginatorLeft}
rows={10} rowsPerPageOptions={[5, 10, 20]}
>
<Column field="name" header="Name" filter style={{ textAlign: 'center', width: '6em' }} />
<Column field="email" header="Email" filter style={{ textAlign: 'center', width: '6em' }} />
<Column field="lastUpdate" header="Last update" style={{ textAlign: 'center', width: '6em' }} />
<Column field="creationDate" header="Creation Date" style={{ textAlign: 'center', width: '6em' }} />
<Column body={this.actionTemplate} header="Actions" style={{ textAlign: 'center', width: '6em' }} />
</DataTable>
);
}
Try:
<Column body={this.actionTemplate.bind(this)} header="Actions" style={{ textAlign: 'center', width: '6em' }} />
My guess is that actionTemplate is called within another object context that's why selectUser is not defined/a function.

Categories

Resources