Reactstrap Collapse not working within React component - javascript

I've been trying to get my React component to work with the Collapse but I cannot seem to get my component to collapse correctly. Right now it will collapse temporarily when the div is clicked, but it will automatically reopen and not actually collapse any of the information needed. This component is taking multiple "modules" and turning them into their own cards. I've tried using a button instead of a div for the "onClick" and have tried with and without the reactstrap Card and CardBody components.
I'm thinking that the useState hook is somehow getting lost with my other props? Any help would be appreciated.
import React, { useState } from "react";
import { Container, Collapse, Card, CardBody } from "reactstrap";
import ReplayCard from "./ReplayCard";
import AttachmentCard from "./AttachmentCard";
const ModuleCard = (props) => {
const module = props.cardID;
const [isOpen, setIsOpen] = useState(false);
const toggle = () => setIsOpen(!isOpen);
return (
<div className="moduleCard">
<div onClick={toggle}>
<h2>{module.m_title}</h2>
<h5>Replay Date: {module.m_date}</h5>
</div>
<Collapse isOpen={isOpen}>
<h5>
{module.m_description}
</h5>
<h3>{module.m_title} Video(s)</h3>
<Container className="ReplayCard" fluid={true}>
{module.m_replay &&
module.m_replay.map((value, index) => {
return (
<ReplayCard
key={index}
cardID={index}
video={value.video}
text={value.text}
/>
);
})}
</Container>
<h3>{module.m_title} Link(s)</h3>
<Container className="AttachmentCard" fluid={true}>
{module.m_attachment &&
module.m_attachment.map((value, index) => {
return (
<AttachmentCard
key={index}
cardID={index}
text={value.text}
link={value.link}
/>
);
})}
</Container>
</Collapse>
</div>
);
};
export default ModuleCard;
The useState does seem to be changing from true to false when a console.log is inserted to the togged but still isn't actually triggering any changes.

Related

ReactJS child components import resolution along with their parent component prefix

Hi folks I'm very curious to find a way for importing parent/child components with the prefix of their parent component using dot notation.
Before taking your much time I would like to show you guys an example from the react-bootstrap components import style.
import Modal from "react-bootstrap";
# usage
function Example() {
return (
<Modal show={show} onHide={handleClose}>
<Modal.Header closeButton>
<Modal.Title>Modal heading</Modal.Title>
</Modal.Header>
<Modal.Body>Woohoo, you're reading this text in a modal!</Modal.Body>
<Modal.Footer></Modal.Footer>
</Modal>
);
}
render(<Example />);
I'm trying to have this kind of a similar approach.
I have a Layout component and within that, I have 3 more child components Header, Body, and Footer.
Right now I'm using them like this
Layout.js
export const Header = ({ children }) => (
<div className="header">{children}</div>
);
export const Body = ({ children }) => <div className="body">{children}</div>;
export const Footer = ({ children }) => (
<div className="footer">{children}</div>
);
export const Layout = ({ children }) => {
return <section>{children}</section>;
};
const _default = {
Header: (props) => <Header {...props} />,
Body: (props) => <Body {...props} />,
Footer: (props) => <Footer {...props} />
};
export default _default;
App.js
import { Layout, Header, Body, Footer } from "./Layout";
import ParentLayout from "./Layout";
export default function App() {
return (
<div className="App">
<Layout>
<Header>Header goes here</Header>
<Body>Body goes here</Body>
<Footer>Footer goes here</Footer>
</Layout>
{/* as you can see from this example i can't use ParentLayout as a componet */}
<Layout>
<ParentLayout.Header>Header goes here</ParentLayout.Header>
<ParentLayout.Body>Body goes here</ParentLayout.Body>
<ParentLayout.Footer>Footer goes here</ParentLayout.Footer>
</Layout>
{/* so i was wondering if it can be done in this way */}
{/*
<ParentLayout>
<ParentLayout.Header>Header goes here</ParentLayout.Header>
<ParentLayout.Body>Body goes here</ParentLayout.Body>
<ParentLayout.Footer>Footer goes here</ParentLayout.Footer>
</ParentLayout>
*/}
</div>
);
}
I have created this playground so you can quickly hit and try.

Can't perform a React state update on an unmounted component with react-router-dom links

I have a Sidenav component that takes in props. These props are then being used to render the custom sidenav for the page it's used on. Everything works, but when clicking on one of the links in the browser, this warning pops up:
It still redirects to the correct page and the page shows up, but the warning shows in the console every time one of the links is clicked. What have i done wrong?
Here is my component code:
import {
Icon,
Menu,
Sidebar,
} from 'semantic-ui-react'
import { useState } from 'react';
import { Link } from 'react-router-dom';
const SideNav = (props) => {
const { title, link_title1, link_route1, link_title2, link_route2, link_title3, link_route3 } = props;
const [visible, setVisible] = useState(false)
const handleToggle = () => {
setVisible(!visible);
};
return (
<>
{visible && props ?
<div>
<Sidebar
className="sidenav"
as={Menu}
animation='overlay'
icon='labeled'
inverted
onHide={() => setVisible(false)}
vertical
visible={visible}
width='thin'
>
<p>{title}</p>
<Link onClick={handleToggle} to={link_route1}>{link_title1}</Link>
<Link onClick={handleToggle} to={link_route2}>{link_title2}</Link>
{link_route3 && link_title3 ?
<Link onClick={handleToggle} to={link_route3}>{link_title3}</Link>
:
''
}
</Sidebar>
<Icon
size="big"
name='caret square left outline'
onClick={handleToggle} />
</div>
:
<Icon
size="big"
name='caret square right outline'
onClick={handleToggle} />
}
</>)}
This is because handleToggle is called after the Link redirects to the other page, trying to update the state ( with setVisible ) on an unmounted component, you should delay the redirect until the toggle happens, here's a good example of how to do that

filtering out onClick from a mapped array

I am trying to figure out how to filter out a mapped array and making the rest of the results disappear in the same component. I've done the same with React Router as I can route the result to a different page but I am wondering if there is a way to do the same on the same component? I have a Directory component (below) that is mapping through an array to display results of items on the page.
I would like to click on one of the elements and remove the rest. I tried to incorporate a filter method in the same component but drawing blanks on how I should implement it. Let me know what you think!
import React from 'react'
import { Card, CardImg} from 'reactstrap'
function Presentational({example, onClick}){
return(
<Card onClick={()=> onClick(example.name) }>
<CardImg src={example.image}/>
</Card>
)
}
function Directory(props){
const examples = props.propExample.map(example=>{
return (
<div>
<Presentational example={example} onClick={props.onClick} />
</div>
)
})
return(
<div>
{examples}
</div>
)
}
export default Directory;
You may use useState hook for selection
We store clicked elements inside the state variable selected. using useState hook.
When the user clicks on the element react component will remember which element he clicked and will render an array from 1 clicked element [selected].
In order to cleanup selection, just call setSelected()
It is the same logic as you want.
import React, {useState} from 'react'
import { Card, CardImg} from 'reactstrap'
function Presentational({example, onClick}){
return(
<Card onClick={()=> onClick(example.name) }>
<CardImg src={example.image}/>
</Card>
)
}
function Directory(props){
const [selected, setSelected] = useState()
const examples = (selected ? [selected] : props.propExample).map(example=>{
return (
<div>
<Presentational example={example} onClick={(name) => {
props.onClick(name)
setSelected(example)
}}
/>
</div>
)
})
return(
<div>
{examples}
</div>
)
}
export default Directory;
if you want to do it with a filter clause it will look almost the same, but with the extra operations
import React, {useState} from 'react'
import { Card, CardImg} from 'reactstrap'
function Presentational({example, onClick}){
return(
<Card onClick={()=> onClick(example.name) }>
<CardImg src={example.image}/>
</Card>
)
}
function Directory(props){
const [selected, setSelected] = useState()
const examples = props.propExample.filter(it => typeof selected === 'undefined' || it.name === selected).map(example=>{
return (
<div>
<Presentational example={example} onClick={(name) => {
props.onClick(name)
setSelected(name)
}}
/>
</div>
)
})
return(
<div>
{examples}
</div>
)
}
export default Directory;

React.js: How to convert class based component to functional?

I'm building an app using function based component. I found the sidebar menu template from Material Ui in classes and want to convert it to functional component. But after converting click button doesn't work. I've only changed the menu icon to another.
Any help will be appreciated.
Here is the default component in classes
import React from "react";
import AppBar from "#material-ui/core/AppBar";
import Toolbar from "#material-ui/core/Toolbar";
import Typography from "#material-ui/core/Typography";
import Button from "#material-ui/core/Button";
import IconButton from "#material-ui/core/IconButton";
import MenuIcon from "#material-ui/icons/Menu";
import { NavDrawer } from "./NavDrawer";
class NavBar extends React.Component {
constructor(props) {
super(props);
this.state = {
drawerOpened: false
};
}
toggleDrawer = booleanValue => () => {
this.setState({
drawerOpened: booleanValue
});
};
render() {
return (
<div className="App">
<AppBar position="static">
<Toolbar>
<IconButton
color="secondary"
aria-label="Menu"
onClick={this.toggleDrawer(true)}
>
<MenuIcon />
</IconButton>
<Typography variant="h6" color="inherit">
News
</Typography>
<Button color="inherit">Login</Button>
</Toolbar>
</AppBar>
<NavDrawer
drawerOpened={this.state.drawerOpened}
toggleDrawer={this.toggleDrawer}
/>
</div>
);
}
}
export default NavBar
Here I'm trying to convert
import React, { useState } from 'react'
import AppBar from '#material-ui/core/AppBar'
import Toolbar from '#material-ui/core/Toolbar'
import Typography from '#material-ui/core/Typography'
import IconButton from '#material-ui/core/IconButton'
import NavDrawer from './NavDrawer'
import AddShoppingCartIcon from '#material-ui/icons/AddShoppingCart'
function NavBar(props) {
const [drawerOpened, setDrawerOpened] = useState(false)
const toggleDrawer = booleanValue => () => {
setDrawerOpened(booleanValue)
}
return (
<div className="App">
<AppBar position="static">
<Toolbar>
<IconButton
aria-label="AddShoppingCartIcon"
onClick={() => toggleDrawer(true)}
>
<AddShoppingCartIcon style={{ fontSize: 30 }} color="secondary" />
</IconButton>
<Typography variant="h6" color="inherit"></Typography>
</Toolbar>
</AppBar>
<NavDrawer drawerOpened={drawerOpened} toggleDrawer={toggleDrawer} />
</div>
)
}
export default NavBar
Have a look at React hooks, there ae two approaches:
const [toggleDrawer, setToggleDrawer] = useState(false); // set variable
<button onClick={() => setToggleDrawer(!toggleDrawer}>
Of you can useEffect to perform some logic after the component is initially rendered, preventing a max error:
const toggleDrawer = false;
useEffect(() => { // update variable
checkDrawOpened(toggleDrawer)
}, toggleDrawer);]
With the one click
onClick={toggleDrawer} // use variable
You can do this instead for toggling actions.
const toggleDrawer = () => {
setDrawerOpened(!drawerOpened)
}
And in the return
onClick={toggleDrawer}
Your function is stacking. On onclick, you try to call function to call function. Just use the const instead.
on toggleDrawer const, you should set setDrawerOpened to whenever the opposite of value it is to get toggling effect.

Passing refs from Component to Component in React

So I am not sure if passing refs would be the best thing to do but it's kinda what I have set-out to do tell me if there is a better option..
So I am trying to have an onClick of a nav link, scroll down to the the div "contactForm".
App.js
import ContactForm from './components/ContactForm'
import ParllaxPage from './components/ParllaxPage'
import NavigationBar from './components/NavigationBar'
import React from 'react';
import './App.css';
const App = () => {
return (
< div cssClass="App" >
<body>
<span><NavigationBar /></span>
<ParllaxPage cssClass="parallax-wrapper" />
<ParllaxPage cssClass="parallax-wrapper parallax-pageOne" />
<ContactForm />
</body >
</div >
);
}
export default App;
I was trying to use forwardRef but I am not sure that I was doing it correctly so...
NavigationBar.js
import ContactForm from "./ContactForm";
import React, { useRef } from "react";
import App from "../App";
import { Nav, Navbar, Form, FormControl, Button } from "react-bootstrap";
const ContactFormRef = React.forwardRef((props, ref) => (
<ContactForm className="contactForm" ref={ref}>
{props.children}
</ContactForm>
));
const scrollToRef = (ref) => ref.current.scrollIntoView({ behavior: "smooth" });
const NavigationBar = () => {
const ref = React.forwardRef(ContactFormRef);
return (
<Navbar bg="light" expand="lg">
<Navbar.Brand href="#home">A1 Gutters</Navbar.Brand>
<Navbar.Toggle aria-controls="b casic-navbar-nav" />
<Nav className="mr-auto">
<Nav.Link href="#home">Home</Nav.Link>
<Nav.Link href="#link">Link</Nav.Link>
<Nav.Link href="#" onClick={console.log(ref)}>
Contact
</Nav.Link>
</Nav>
</Navbar>
);
};
export default NavigationBar;
I don't think the other files really need to be shown, I am just trying to get the className out of the ContactForm component so I can scroll to it onClick.. I currently just have a console.log in the onClick.
Using Hooks will simplify here.
Have state variable for gotoContact and ref for contactRef
Add click handler for navigation link contact
Add useEffect hook and when ever use click on contact and ref is available (value in ref.current) then call the scroll to view)
import ContactForm from "./components/ContactForm";
import ParllaxPage from "./components/ParllaxPage";
import React, { useState, useEffect, useRef } from "react";
import "./App.css";
const NavigationBar = ({ onClickContact }) => {
return (
<Navbar bg="light" expand="lg">
<Navbar.Brand href="#home">A1 Gutters</Navbar.Brand>
<Navbar.Toggle aria-controls="b casic-navbar-nav" />
<Nav className="mr-auto">
<Nav.Link href="#home">Home</Nav.Link>
<Nav.Link href="#link">Link</Nav.Link>
<Nav.Link href="#" onClick={() => onClickContact()}>
Contact
</Nav.Link>
</Nav>
</Navbar>
);
};
const App = () => {
const [gotoContact, setGotoContact] = useState(false);
const contactRef = useRef(null);
useEffect(() => {
if (gotoContact && contactRef.current) {
contactRef.current.scrollIntoView();
setGotoContact(false);
}
}, [gotoContact, contactRef.current]);
return (
<div cssClass="App">
<body>
<span>
<NavigationBar onClickContact={() => setGotoContact(true)} />
</span>
<ParllaxPage cssClass="parallax-wrapper" />
<ParllaxPage cssClass="parallax-wrapper parallax-pageOne" />
<div ref={contactRef}>
<ContactForm />
</div>
</body>
</div>
);
};
export default App;
You should identify the div "contactForm" with an id and have an anchor tag point to it:
<div id="contactForm"></div>
You can add scroll-behaviour: smooth to the body in CSS
No need to create a separate ContactFormRef wrapper. Simply use React.forwardRef in ContactForm itself. Those not passing a ref will not have to know it forwards refs.
Then, remember to further pass the ref received to a native element or use useImperativeHandle hook to add methods to it without passing it further down.
const ref = React.forwardRef(ContactFormRef)
This is wrong.
You should do it the same as with native components:
const ref = useRef()
return <ContactForm ref={ref} >
// etc
</ContactForm>
You are not rendering the ContactFormRef, so the reference points no nothing!
App.js should be like:
...
const App = () => {
const myNestedRefRef=React.useRef();
return (
...
<NavigationBar contactRef={myNestedRefRef}/>
...
<ContactForm ref={myNestedRefRef} />
...
);
}
...
ContactForm.js
...
function ContactForm=React.forwardRef((props, ref) => (
<form ref={ref}>
...
</form>
));
NavigationBar.js
const NavigationBar = ({contactRef}) => {
return (
...
<Nav.Link href="#" onClick={console.log(contactRef)}>
...
);
};
Consider that
If the <ContactForm/> hasn't been rendered yet, the ref will look like {current:null}

Categories