Call a Function on Tab click based on key? - javascript

These are my tabs and tables and I want to call different functions based on tabKey when you click on the tab.
<Paper className={classes.root} style = {{paddingTop:50}}>
<Grid>
<TabSelector
displayType="button"
showTab={"Org Details"}
showCount={false}
highlightTab={true}
onClick={() => this.getTabs.bind(this)}
>
<Tab name="Org Details" tabKey="gridOrgDetails">
<p>
<Grid>
<Paper className={classes.root} style={{ paddingTop: 50 }}>
<a href="#gridOrgDetails" id="gridOrgDetails" />
<Paper style={{ backgroundColor: "#759FEB" }}>
<Typography> ORG Details </Typography>
</Paper>
<EnhancedTable
checkBoxEnabled={false}
Data={{ rows: this.getOrg(), headCells: orgDeatils }}
rowsPerPage={5}
orderBy="Call_Date_vod__c"
order="desc"
/>
</Paper>
</Grid>
</p>
</Tab>
<Tab
name="License Details"
tabKey="gridLicenseDetails"
onClick={() => this.getLicenseDetails()}
>
<p>
<Grid>
<Paper className={classes.root} style={{ paddingTop: 50 }}>
<a href="#gridLicenseDetails" id="gridLicenseDetails" />
<Paper style={{ backgroundColor: "#759FEB" }}>
<Typography> License Details </Typography>
</Paper>
<EnhancedTable
checkBoxEnabled={false}
Data={{ rows: this.getOrg(), headCells: licenseDetails }}
rowsPerPage={5}
orderBy="Call_Date_vod__c"
order="desc"
/>
</Paper>
</Grid>
</p>
</Tab>
</TabSelector>;
This is my function where I am switching keys but this seems to be not working.
Can anyone please help me?
getTabs(f){
console.log(f.tabKey)
switch(f.tabKey) {
case "gridOrgDetails":
return this.getOrgDetails();
break;
case "gridLicenseDetails":
return this.getLicenseDetails();
break;
}
}

Here's a basic representation of what you're trying to achieve jsFiddle
link
const User = (props) => <div onClick = {props.onClick}>I am user
{props.user}</div>
class App extends React.Component {
constructor(props) {
super(props)
}
getTabs(f){
switch(f) {
case "gridOrgDetails":
console.log("gridOrgDetails")
break;
case "gridLicenseDetails":
console.log("gridLicenseDetails")
break;
}
}
render() {
return (
<div>
<div >
<User user="a" onClick={this.getTabs.bind(this,"gridOrgDetails")} />
<User user="b" onClick={this.getTabs.bind(this, "gridLicenseDetails")}/>
</div>
</div>
)
}
}
ReactDOM.render(<App />, document.querySelector("#app"))

Related

'text' is missing in props validation react/prop-types

as you may get from the title, passing props in react is not working. And i donĀ“t get why.
function Global(props) {
return (
<div>
<ResponsiveAppBar />
<Grid sx={{ mt: 7 }}>
{props.text}
<HorizontalLinearStepper />
</Grid>
</div>
);
}
return (
<div className="App">
<Card>
<CvContext.Provider value={value}>
<Global text="kk" />
</CvContext.Provider>
</Card>
</div>
);
Try destructuring the props like this:
function Global({text}) {
return (
<div>
<ResponsiveAppBar />
<Grid sx={{ mt: 7 }}>
{text}
<HorizontalLinearStepper />
</Grid>
</div>
);
}
You can keep the rest the same. Destructuring props is (usually) a better practice.
Does it work if you do
import PropTypes from 'prop-types';
function Global(props) {
return (
<div>
<ResponsiveAppBar />
<Grid sx={{ mt: 7 }}>
{props.text}
<HorizontalLinearStepper />
</Grid>
</div>
);
}
Global.propTypes = {
text: PropTypes.string
}
But your code should work even without it, although you would be getting that warning.
this correction work for me
import PropTypes from "prop-types";
function Global(props) {
Global.propTypes = {
text: PropTypes.string,
};
return (
<div>
<ResponsiveAppBar />
<Grid sx={{ mt: 7 }}>
{props.text}
<HorizontalLinearStepper />
</Grid>
</div>
);
}
export default Global;

Not able to see the updated values in react after creating a group

I am trying to perform a simple exercise, wherein I am showing the data from the local JSON file saved in my folder, and then reading it to show the data with useState, such that when a user clicks in he can edit the author and location filed and save it.
The issue I get is when I save the data in my group or location it does not populate the new value, however, it just removes the new value, but when I filter and select all values from the dropdown I can see the values in there.
Can anyone please let me know what is the missing part here? I want to achieve the task that when a user updates the value on the author group or location group they should be there with the new group value.
Please the link to the code below and a working demo on codeSandbox
watch the full code and demo here
The source code for the author group component I tried so far;
import { useEffect, useState } from "react";
import {
Container,
Accordion,
AccordionSummary,
AccordionDetails,
Typography,
Button
} from "#mui/material";
import ExpandMoreIcon from "#mui/icons-material/ExpandMore";
import EditIcon from "#mui/icons-material/Edit";
const Authorsgroup = ({
posts,
groupDropdownValue,
setShowForm,
setPostId,
showForm
}) => {
const authorGroup = posts.reduce((group, authorgroup) => {
(group[authorgroup.author.replace(/ +/g, "")] =
group[authorgroup.author.replace(/ +/g, "")] || []).push(authorgroup);
return group;
}, {});
const [authorGroupValues, setAuthorGroupValues] = useState(authorGroup);
useEffect(() => {
setAuthorGroupValues(authorGroup);
console.log(authorGroupValues);
}, [groupDropdownValue, showForm]);
return (
<>
{/* all gorupby authors */}
<Container>
{/* show group of Tapesh */}
<Container style={{ marginTop: "3rem" }}>
{authorGroupValues?.Tapesh.map((post, index) => (
<Accordion key={index}>
<AccordionSummary
expandIcon={<ExpandMoreIcon />}
aria-controls="panel1a-content"
id="panel1a-header"
>
<Typography variant="h6" style={{ color: "#EB1283" }}>
{post.id} {post.author} {post.location}
</Typography>
</AccordionSummary>
<AccordionDetails>
<Typography variant="h4">{post.location}</Typography>
<Typography>{post.text}</Typography>
<Button
variant="outlined"
onClick={() => {
setShowForm(!showForm);
setPostId(post.id);
}}
startIcon={<EditIcon />}
>
Edit
</Button>
</AccordionDetails>
</Accordion>
))}
</Container>
{/* show group of HappyManager */}
<Container style={{ marginTop: "3rem" }}>
{authorGroupValues?.HappyManager.map((post, index) => (
<Accordion key={index}>
<AccordionSummary
expandIcon={<ExpandMoreIcon />}
aria-controls="panel1a-content"
id="panel1a-header"
>
<Typography variant="h6" style={{ color: "orange" }}>
{post.id} {post.author} {post.location}
</Typography>
</AccordionSummary>
<AccordionDetails>
<Typography variant="h4">{post.location}</Typography>
<Typography>{post.text}</Typography>
<Button
variant="outlined"
onClick={() => {
setShowForm(!showForm);
setPostId(post.id);
}}
startIcon={<EditIcon />}
>
Edit
</Button>
</AccordionDetails>
</Accordion>
))}
</Container>
{/* show group of HappyDeveloper */}
<Container style={{ marginTop: "3rem" }}>
{authorGroupValues?.HappyDeveloper.map((post, index) => (
<Accordion key={index}>
<AccordionSummary
expandIcon={<ExpandMoreIcon />}
aria-controls="panel1a-content"
id="panel1a-header"
>
<Typography variant="h6" style={{ color: "green" }}>
{post.id} {post.author} {post.location}
</Typography>
</AccordionSummary>
<AccordionDetails>
<Typography variant="h4">{post.location}</Typography>
<Typography>{post.text}</Typography>
<Button
variant="outlined"
onClick={() => {
setShowForm(!showForm);
setPostId(post.id);
}}
startIcon={<EditIcon />}
>
Edit
</Button>
</AccordionDetails>
</Accordion>
))}
</Container>
{/* show group of HappyUser */}
<Container style={{ marginTop: "3rem" }}>
{authorGroupValues?.HappyUser.map((post, index) => (
<Accordion key={index}>
<AccordionSummary
expandIcon={<ExpandMoreIcon />}
aria-controls="panel1a-content"
id="panel1a-header"
>
<Typography variant="h6" style={{ color: "red" }}>
{post.id} {post.author} {post.location}
</Typography>
</AccordionSummary>
<AccordionDetails>
<Typography variant="h4">{post.location}</Typography>
<Typography>{post.text}</Typography>
<Button
variant="outlined"
onClick={() => {
setShowForm(!showForm);
setPostId(post.id);
}}
startIcon={<EditIcon />}
>
Edit
</Button>
</AccordionDetails>
</Accordion>
))}
</Container>
</Container>
</>
);
};
export default Authorsgroup;
Thanks any suggestions or help are really appreciated.

Trying to pass props to an axios call

I am building a forum and I want to make it where: Once you click on the title, it displays a page (which I already created) that displays the post title and then the post body. I used MUI to build the page as well. However, the Axios call fails when I call the backend and appending the "this.state.props." to the end.
My "All Questions" page code in which the user which select which post to open:
export default class DisplayPosts extends Component {
constructor(props) {
super(props);
this.state = {
posts: [],
selectedPostId: null,
};
}
componentDidMount (){
axios.get('http://localhost:6006/api/v1/posts')
.then(res=> {
const posts = [];
for (let key in res.data.data) {
posts.push({...res.data.data[key], id: key});
}
this.setState({
posts: posts,
})
console.log('Pulling From:: ', res.data.data)
})
.catch(err => console.log('err:: ', err)
)
}
onPostClickHandler = (_id) => {
this.setState({
selectedPostId: _id,
})
console.log(_id)
}
render() {
const posts = this.state.posts.map((post) => {
return <Posts
key ={post._id}
post={post}
postclicked = {this.onPostClickHandler.bind(
this,
post._id,
)} />;
})
return (
<Box component="main"
sx={{ flexGrow: 1, p: 3, marginLeft: "300px",marginTop:"-40px" }}>
<Toolbar />
<Stack spacing={2}>
<Typography>
<h1> All Questions </h1>
</Typography>
<Button
sx={{}}
variant = 'outlined'
size = 'medium'
color = 'secondary'>
Ask New Question
</Button>
<Divider />
<div>
{posts}
</div>
</Stack>
{this.state.selectedPostId && (
<ViewPosts _id={this.state.selectedPostId} />
)}
</Box>
)
}
}
My "View Posts" page, the page where the user will see the information of the post they just clicked
export default class ViewPosts extends Component {
constructor(props){
super(props);
this.state = {
post: null,
}
}
componentDidMount (){
axios.get(`http://localhost:6006/api/v1/posts/${this.props._id}`)
.then(res=> {
this.setState({
posts: {...res.data.data, _id: this.props._id}
})
console.log('Pulling From:: ', res.data.data)
})
.catch(err => console.log('err:: ', err)
)
}
render() {
return (
<div>
<><Box component="main"
sx={{ flexGrow: 1, p: 3, marginLeft: "300px", marginTop: "-40px" }}>
<Toolbar />
<Typography>
<h1>{this.state.post.title} </h1>
<p>Added: Today ..........Viewed: -- times </p>
</Typography>
<Divider />
<Stack direction='row' spacing={3}>
<Stack
direction="column"
spacing={2}>
<IconButton>
<KeyboardDoubleArrowUpIcon color='primary' />
</IconButton>
<IconButton sx={{ marginTop: '2px' }}>
<KeyboardDoubleArrowDownIcon color='primary' />
</IconButton>
</Stack>
<Typography>
<h6> </h6>
</Typography>
<Typography>
<p>
{this.state.post.body}
</p>
</Typography>
</Stack>
<Divider />
<TextField
sx={{ marginTop: "20px", marginLeft: "0px", width: '950px' }}
id="filled-multiline-static"
label="Enter Answer Here..."
multiline
rows={8}
variant="filled" />
<Button
sx={{ marginTop: "15px" }}
variant='contained'
size='large'
color='primary'
>
Post Your Answer
</Button>
</Box>
</>
</div>
)
}
}
From my understanding, componentDidMount is called after the component is mounted.
And by that, I mean the axios call will happen immediately, while the DOM content will take more time to load.
So, chances are, what happens is that you're not going to see anything, even if the axios call is finished and the state of the ViewPost is no longer null.
What you may wanna do now is to create a logic that prevents the DOM of the post from being displayed until the state is populated.
Like, for example...
render() {
return this.state.post && (
<div>
<><Box component="main"
sx={{ flexGrow: 1, p: 3, marginLeft: "300px", marginTop: "-40px" }}>
<Toolbar />
<Typography>
<h1>{this.state.post.title} </h1>
<p>Added: Today ..........Viewed: -- times </p>
</Typography>
<Divider />
<Stack direction='row' spacing={3}>
<Stack
direction="column"
spacing={2}>
<IconButton>
<KeyboardDoubleArrowUpIcon color='primary' />
</IconButton>
<IconButton sx={{ marginTop: '2px' }}>
<KeyboardDoubleArrowDownIcon color='primary' />
</IconButton>
</Stack>
<Typography>
<h6> </h6>
</Typography>
<Typography>
<p>
{this.state.post.body}
</p>
</Typography>
</Stack>
<Divider />
<TextField
sx={{ marginTop: "20px", marginLeft: "0px", width: '950px' }}
id="filled-multiline-static"
label="Enter Answer Here..."
multiline
rows={8}
variant="filled" />
<Button
sx={{ marginTop: "15px" }}
variant='contained'
size='large'
color='primary'
>
Post Your Answer
</Button>
</Box>
</>
</div>
)
}
}

React DnD, could not find "store" in the context of Connect(Droppable)

Hello I am trying to make a drag and drop in my application but I have got a huge error. I have no idea if property is missing because in IDE it is an error free code.
Uncaught Error: Could not find "store" in the context of "Connect(Droppable)". Either wrap the root component in a <Provider>, or pass a custom React context provider to <Provider> and the corresponding React context consumer to Connect(Droppable) in connect options.
Down here are my components
3 Columns ( I want drag and drop across one column each, not between them)
const DetailColumns: React.FC<funcProps> = (props) => {
const onDragEnd = () => {};
return (
<Box
h="80vh"
borderWidth="0.5rem"
borderColor="orange.300"
borderRadius="1rem"
w="80%"
marginTop="2rem"
>
<Grid w="100%" h="100%" templateColumns="60% 20% 20%">
<Box border="0.5rem" borderColor="orange.300">
<RecipeDescriptionBox recipe={props.recipe} />
</Box>
<Box borderLeftWidth="0.5rem" borderColor="orange.300">
<RecipeStepsBox recipe={props.recipe} />
</Box>
<DragDropContext onDragEnd={onDragEnd}>
<Box borderLeftWidth="0.5rem" borderColor="orange.300">
<RecipeIngredientsBox recipe={props.recipe} />
</Box>
</DragDropContext>
</Grid>
</Box>
);
};
List of Items
<Box>
<ColumnHeader title="Steps" />
<Droppable droppableId="unique">
{(provided) => (
<Box {...provided.droppableProps} innerRef={provided.innerRef}>
{steps.map((step, index) => (
<DetailListItem
key={step}
itemName={step}
indexOfItem={index}
id={Math.random().toString()}
/>
))}
{provided.placeholder}
</Box>
)}
</Droppable>
</Box>
Item element
<Draggable draggableId={props.id} index={props.indexOfItem}>
{(provided) => (
<Box
{...provided.draggableProps}
{...provided.dragHandleProps}
innerRef={provided.innerRef}
>
<Flex margin="1rem">
<Box
bgGradient="linear(to-r, orange.200, orange.400)"
height="6vh"
width="6vh"
boxShadow="md"
rounded="md"
>
<Grid w="100%" h="100%" placeItems="center">
<Text color="white" fontWeight="700" fontSize="140%">
{props.amount && props.amount + props.unit}
{!props.amount && props.indexOfItem}
</Text>
</Grid>
</Box>
<Grid placeItems="center">
<Text marginLeft="1rem" fontWeight="500" fontSize="1.8rem">
{props.itemName}
</Text>
</Grid>
</Flex>
</Box>
)}
</Draggable>
If you want I can put this code to some sandbox to make it easier to debug.

Handling onClick for a particular element in react

I am trying to make a card grid where the user can expand the card to view its details. The issue I am facing with the react hooks is that the function is getting called for all cards instead of the particular card I am clicking the button. As a result, all the cards are getting expanded.
Here's my code for reference.
Any help is highly appreciated. Thank you!
function Album(props) {
return (
<div>
<Card className={classes.card}>
<Card.Text >
<p className={classes.heading}>
{props.blogTitle}
</p>
</Card.Text>
<Card.Body>
<Card.Img
src={props.imgsrc}
alt="Card image"
className={classes.cardMedia}
/>
{props.cardOpen &&
<AnimatePresence>
<motion.div
initial={{opacity:0}}
animate={{opacity:1, transition:0.3}}
>
<p className={classes.desc} gutterbottom>
{props.blogDescription}
</p>
<div href={props.blogLink}
style={{color:"gray", fontSize:17, fontFamily:"calibri", fontSmooth: "auto", cursor:"pointer", display:"flex", justifyContent:"center"}}>
<LocalLibraryIcon style={{marginRight:7}}/>Read blog
</div>
</motion.div>
</AnimatePresence>
}
{(props.cardOpen) ?
<div onClick={props.isOpen} style={{float:"right", cursor:"pointer"}}>
<ExpandLessIcon style={{fontSize:40, marginTop:10, color:" #909090"}}/>
</div> : (
<div onClick={props.isOpen} style={{float:"right", cursor:"pointer"}}>
<ExpandMoreIcon style={{fontSize:40, marginTop:10, color:" #909090"}}/>
</div>
)}
</Card.Body>
</Card>
</div>
);
}
export default function ProjectItems() {
const [cardOpen, setCardOpen]= useState(false);
return (
<React.Fragment>
<CssBaseline />
<main>
<div className={classes.heroContent}>
<Container maxWidth="md">
<Typography
variant="h2"
align="center"
color="textPrimary"
className={classes.root}
gutterBottom
>
Blogs
</Typography>
</Container>
</div>
<Container maxWidth="md">
<Grid container spacing={4}>
{blogData.map(post => (
<Grid item xs={12} sm={6} md={4} key={post.id}>
<div>
<Album
blogId={post.id}
blogTitle={post.title}
blogDescription={post.summary}
imgsrc={post.image_link}
blogLink={post.article_link}
isOpen={()=>{
setCardOpen(!cardOpen);
}}
cardOpen={cardOpen}
/>
</div>
</Grid>
))}
</Grid>
</Container>
</main>
</React.Fragment>
);
}

Categories