After removing the text area, not able to add again or add other options in a react app - reactjs

On click on the Text Area, button should add relevant text area in a pag. By clicking on the close button, system should remove the added textarea in a React page. By default, the close button shouldn't display. In this example, system is adding the text area, but once it is removed, I am not able to add the textarea anymore. Could someone please advise the issue here.
CSB link:
https://codesandbox.io/s/nervous-currying-jojdhi?file=/src/App.js
import "./styles.css";
import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
export default function App() {
const [multiInput, setMultiInput] = useState("");
const [createCode, setCreateCode] = useState("");
const [createImageTag, setImageTag] = useState("");
const [visible, setVisible] = useState(true);
const createCodeSection = () => {
const newElement = React.createElement("blockquote", {
contenteditable: "true",
className: "codehighlight",
name: "codesection" + new Date().getTime()
});
setCreateCode((createCode) => [...createCode, newElement]);
};
const createMultilineTextSection = () => {
const newElement = React.createElement("textarea", {
contenteditable: "true",
className: "defaultTextArea",
name: "textarea" + new Date().getTime()
});
setCreateCode((multiInput) => [...multiInput, newElement]);
};
const createImageSection = () => {
const newElement = React.createElement("img", {
key: "ele" + new Date().getTime()
});
setCreateCode((createImageTag) => [...createImageTag, newElement]);
};
const removeElement = () => {
setVisible((prev) => !prev);
};
return (
<div id="App">
<div className="adminSection">
<div className="row">
<div className="logout"></div>
<div className="createBlogSection">
<div className="row">
<button onClick={createMultilineTextSection}>Text Area</button>
<button onClick={createCodeSection}>Code</button>
<button>Image</button>
</div>{" "}
<br></br>
<div className="row">
<textarea className="defaultTextArea"></textarea>
</div>
<br></br>
<div className="row">
{visible && <span className="dtextArea">{createCode}</span>}
</div>
<div className="row">
{visible && (
<div>
<span className="closeElement">
<button onClick={removeElement}>X</button>
</span>
<span>{multiInput}</span>
</div>
)}
</div>
</div>
</div>
</div>
</div>
);
}
//css
.App {
font-family: sans-serif;
text-align: center;
}
.adminSection {
width: 100%;
}
.adminSection h1 {
margin: 25px 0px 0px 550px !important;
color: black !important;
}
.logout img {
height: 30px;
width: 30px;
margin: -100px 50px 0px 0px;
float: right;
}
.createBlogSection {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(700px, 1fr));
grid-gap: 25px !important;
margin: 100px 20px 10px 20px !important;
/* border: solid 1px; */
border-color: #e2e8f0;
border-radius: 0px 5px 5px 0px !important;
background-color: #fff;
}
.defaultTextArea {
height: 100px;
width: 300px;
margin: 10px 0px 10px 40px;
display: flex;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
background-color: #fff !important;
}
.codehighlight {
width: 100%;
color: #fff;
display: flex;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
background-color: #353232 !important;
}
.closeElement {
margin-left: 320px;
display: none;
}

Instead of how you've put the added elements, use:
const removeElement = (index) => {
const newElements = multiInput.filter((_, i) => i == index);
setMultiInput(newElements);
};
// Inside "return" (createBlogSection div)
multiInput.map((_input, index) => {
<div key={index}>
{_input}
<span className="closeElement">
<button onClick={removeElement(index)}>X</button>
</span>
</div>
})
Edit:
Add const [multiInput, setMultiInput] = useState([]); and instead of pushing new elements into separate variables add all into multiInput only. Using setMultiInput(multiInput) => [...multiInput, newElement]); in each case.

Related

Closing modal window by clicking on backdrop (ReactJS)

Could you please help me with one issue? I'd like to make a closing modal window by clicking on backdrop (using ReactJS). But in result window is closing even i click on modal window (at any position).
Here is my code:
import React from "react";
import { Fragment } from "react";
import ReactDOM from "react-dom";
import "./_Modal.scss";
const Backdrop = (props) => {
return (
<div className="backdrop" onClick={props.onClose}>
{props.children}
</div>
);
};
const ModalOverlay = (props) => {
return <div className="modal">{props.children}</div>;
};
const portalItem = document.getElementById("overlays");
const Modal = (props) => {
return (
<Fragment>
{ReactDOM.createPortal(
<Backdrop onClose={props.onClose}>
<ModalOverlay>{props.children}</ModalOverlay>
</Backdrop>,
portalItem
)}
</Fragment>
);
};
export default Modal;
And here is CSS:
.backdrop {
position: fixed;
top:0;
left: 0;
width: 100%;
height: 100vh;
z-index: 20;
background-color: rgba(0,0,0, 0.7);
display: flex;
justify-content: center;
align-items: flex-start;
overflow: auto;
padding-bottom: 15vh;
}
.modal {
position: relative;
max-width: 70%;
top: 5vh;
background-color: $darkgrey;
padding: 1rem;
border-radius: 1.5rem;
box-shadow: 0 1rem 1rem rgba(0,0,0, 0.25);
z-index: 30;
}
}
I'm just start to learning frontend, therefore do not judge strictly )
Just for understanding other people: after adding event.stopPropagation() in ModalOverlay everything works!
const ModalOverlay = (props) => {
return (
<div
className="modal"
onClick={(event) => {
event.stopPropagation();
}}
>
{props.children}
</div>
);
};

How do I Setup a excel like filter using react-data-table-component

Been searching on how to make a excel like filter using react-data-table-component, and found something interesting, like Data Table filtering using react-data-table-component.
Unfortunately, the FilterComponent Component seems to be deprecated, since I can't find anything regarding it but broken links, which is weird for such a interesting feature.
My code is the following:
const columns = Properties.columns;
const getSubHeaderComponent = () => {
return (
<FilterComponent
onFilter={(e) => {
let newFilterText = e.target.value;
filteredItems = statements.filter(
(item) =>
item.name &&
item.name.toLowerCase().includes(newFilterText.toLowerCase())
);
this.setState({ filterText: newFilterText });
}}
onClear={handleClear}
filterText={filterText}
/>
);
};
return (
<div>
<div className="row justify-content-md-center statements-table">
<div className="col-md-10">
<DataTable
columns={columns}
data={statements}
customStyles={Properties.customStyles}
fixedHeader
fixedHeaderScrollHeight="47em"
pagination
subheader
subHeaderComponent={getSubHeaderComponent()}
paginationPerPage={100}
paginationRowsPerPageOptions={[100, 500, 1000]}
subHeader
noHeader
/>
</div>
</div>
Any suggestions?
FilterComponent could be something as simple as
const FilterComponent = ({ filterText, onFilter, onClear }) => (
<div>
<input
type="text"
value={filterText}
onChange={onFilter}
/>
<button type="button" onClick={onClear}>
X
</button>
</div>
);
However, I found following official implementation of FilterComponent on Examples/Filtering | React Data Table Components (also referred Button.js) if you need it like that.
const TextField = styled.input`
height: 32px;
width: 200px;
border-radius: 3px;
border-top-left-radius: 5px;
border-bottom-left-radius: 5px;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
border: 1px solid #e5e5e5;
padding: 0 32px 0 16px;
&:hover {
cursor: pointer;
}
`;
const ButtonStyle = styled.button`
background-color: #2979ff;
border: none;
color: white;
padding: 8px 32px 8px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
border-radius: 3px;
&:hover {
cursor: pointer;
}
`;
const Button = ({ children, ...rest }) => <ButtonStyle {...rest}>{children}</ButtonStyle>;
const ClearButton = styled(Button)`
border-top-left-radius: 0;
border-bottom-left-radius: 0;
border-top-right-radius: 5px;
border-bottom-right-radius: 5px;
height: 34px;
width: 32px;
text-align: center;
display: flex;
align-items: center;
justify-content: center;
`;
const FilterComponent = ({ filterText, onFilter, onClear }) => (
<>
<TextField
id="search"
type="text"
placeholder="Filter By Name"
aria-label="Search Input"
value={filterText}
onChange={onFilter}
/>
<ClearButton type="button" onClick={onClear}>
X
</ClearButton>
</>
);

REACT creating a basic application where I can set a value

I am very new to REACT and I followed a tutorial where I create a generic app where you can increase / decrease the value.
the html:
<head>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat:400,400i,700">
<!-- Code by Angela Delise
https://codepen.io/angeladelise/pen/zYKpRqE
-->
</head>
<body>
<div id="root"></div>
</body>
the css:
/* color variables */
$clr-negative: #ff1744;
$clr-positive: #2abf77;
$clr-gray100: #f0f7f8;
$clr-gray200: #cfd8dc;
$clr-gray300: #a7b7be;
$clr-gray400: #6b7e86;
$clr-gray500: #425a65;
/* border radius */
$radius: 0.2rem;
*,
*::before,
*::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
.app {
font-family: Montserrat, sans-serif;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap: 2rem;
height: 100vh;
background-color: $clr-gray100;
color: $clr-gray500;
}
h1 {
font-size: 6rem;
}
.button__wrapper {
display: flex;
gap: 1rem;
& > * {
border: none;
background-color: white;
box-shadow: 0px 0px 10px $clr-gray200;
font-weight: bold;
font-size: 2rem;
color: inherit;
border-radius: 50%;
outline: none;
height: 4rem;
width: 4rem;
cursor: pointer;
transition: background-color 250ms ease-in-out, transform 50ms ease-in-out;
&:hover {
background-color: $clr-gray200;
}
&:active {
transform: scale(0.9);
}
&:focus {
box-shadow: 0 0 0 3px $clr-gray500;
}
}
}
.negative {
color: $clr-negative;
animation: pulse 500ms ease-in-out;
}
.positive {
color: $clr-positive;
animation: pulse 500ms ease-in-out;
}
#keyframes pulse {
0%,
100% {
transform: scale(1);
}
50% {
transform: scale(1.2);
}
}
JS:
const { useState } = React;
function App() {
const [count, setCount] = useState(0);
return (
<div className="app">
{
// if else statement to determine color of the counter
}
<h1 className={count > 0 ? "positive" : count < 0 ? "negative" : null}>
{count}
</h1>
<div className="button__wrapper">
<button onClick={() => setCount(count - 1)}>-</button>
<button onClick={() => setCount(count + 1)}>+</button>
</div>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
I modify/build from this code and add a text box where I can enter my own value from where it will start from and then have an additional button that I can click to assign that value.
I am not entirely sure on how to implement this feature
If you have to assign the value from the input then you should use uncontrolled input and get the value of the input using useRef hook on button click.
Live Demo
export default function App() {
const inputRef = useRef(); // CHANGE
const [count, setCount] = useState(0);
const assignCustomInput = () => { // CHANGE
const value = inputRef.current.value;
setCount(+value);
};
return (
<div className="app">
<div className="custom-input-wrapper"> // CHANGE
<input type="number" ref={inputRef} />
<button onClick={assignCustomInput}>Assign</button>
</div>
<h1 className={count > 0 ? "positive" : count < 0 ? "negative" : null}>
{count}
</h1>
<div className="button__wrapper">
<button onClick={() => setCount((count) => count - 1)}>-</button>
<button onClick={() => setCount((count) => count + 1)}>+</button>
</div>
</div>
);
}
So you have to create an controlled input for that as shown in below:
const { useState } = React;
function App() {
const [count, setCount] = useState(0);
const handleChange = (evt) => {
setCount(evt.target.value)
}
return (
<div className="app">
{
// if else statement to determine color of the counter
}
<input type="number" value={count} onChange={handleChange} />
<h1 className={count > 0 ? "positive" : count < 0 ? "negative" : null}>
{count}
</h1>
<div className="button__wrapper">
<button onClick={() => setCount(count - 1)}>-</button>
<button onClick={() => setCount(count + 1)}>+</button>
</div>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));

Input checkbox didn't work what I expected

I tried to make an input checkbox when I click the input checkbox, it should be displayed a check image like this.
However, it didn't show the checkbox and I am not sure how to check that the input box was checked or not. Could you help me with what part do I missed and where is something wrong?
I really appreciate your help!
This is CSS inputl and label part
.colors {
display: flex;
flex-direction: column;
span {
margin-bottom: 20px;
}
.colorLists {
margin-left: 10px;
display: flex;
flex-wrap: wrap;
.colorLayout {
display: flex;
flex-direction: column;
position: relative;
width: 33%;
height: 80px;
flex-shrink: 0;
align-items: center;
justify-content: center;
.checkboxLabel {
background-color: beige;
border: 1px solid #ccc;
border-radius: 50%;
cursor: pointer;
height: 28px;
left: 0;
position: absolute;
top: 40;
width: 28px;
&:after {
border: 2px solid #fff;
border-top: none;
border-right: none;
content: '';
height: 6px;
left: 7px;
opacity: 0;
position: absolute;
top: 8px;
transform: rotate(-45deg);
width: 12px;
// opacity: 0.2;
}
}
input[type='checkbox'] {
visibility: hidden;
}
input[type='checkbox']:checked {
& + label {
background-color: beige;
border-color: beige;
&:after {
opacity: 1;
}
}
}
.productColor {
margin-top: 70px;
font-size: 13px;
margin-right: 21px;
}
}
}
}
.sizes {
.HorizontalLine {
margin-top: 25px;
}
.span {
}
.sizeLists {
margin-top: 20px;
margin-bottom: 20px;
button {
margin: 5px;
width: 44px;
height: 32px;
background-color: white;
border: 1px solid silver;
border-radius: 15%;
}
}
}
This is js part
<div className="colors">
<span>색상</span>
<ul className="colorLists">
{COLOR_LISTS.map((color, idx) => {
return (
<li className="colorLayout" key={idx}>
<input type="checkbox" />
<label
className="checkboxLabel"
for="checkbox"
style={{ backgroundColor: color.colorProps }}
/>
<span className="productColor">{color.color_name}</span>
</li>
);
})}
</ul>
</div>
In react you have to set the htmlFor property for the label instead of for.
The value should be the same as the id from the input.
Then you can add a value property for the input which is used for adding/removing the item in the list of selected items.
For this purpose a handleChange function can be defined.
const [selectedItems, setSelectedItems] = useState([]);
function handleChange(e) {
let newSelected = [];
if (selectedItems.includes(e.target.value)) {
newSelected = selectedItems.filter((item) => item !== e.target.value);
} else {
newSelected = [...selectedItems, e.target.value];
}
setSelectedItems(newSelected);
}
return (
<div className="colors">
<span>색상</span>
<ul className="colorLists">
{COLOR_LISTS.map((color, idx) => {
return (
<li className="colorLayout" key={idx}>
<input
onChange={handleChange}
type="checkbox"
id={idx}
value={color.color_name}
checked={selectedItems.includes(color.color_name)}
/>
<label
className="checkboxLabel"
htmlFor={idx}
style={{ backgroundColor: color.colorProps }}
/>
<span className="productColor">{color.color_name}</span>
</li>
);
})}
</ul>
</div>
);
EDIT: Since you are using a class component it can be rewrittenlike this:
export default class CheckboxListComponent extends Component {
constructor(props) {
super(props);
this.state = { selectedItems: [] };
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
let newSelected = [];
if (this.state.selectedItems.includes(e.target.value)) {
newSelected = this.state.selectedItems.filter(
(item) => item !== e.target.value
);
} else {
newSelected = [...this.state.selectedItems, e.target.value];
}
this.setState({ selectedItems: newSelected });
}
render() {
return (
<div className="colors">
<span>색상</span>
<ul className="colorLists">
{COLOR_LISTS.map((color, idx) => {
return (
<li className="colorLayout" key={idx}>
<input
onChange={this.handleChange}
type="checkbox"
id={idx}
value={color.color_name}
checked={this.state.selectedItems.includes(color.color_name)}
/>
<label
className="checkboxLabel"
htmlFor={idx}
style={{ backgroundColor: color.colorProps }}
/>
<span className="productColor">{color.color_name}</span>
</li>
);
})}
</ul>
</div>
);
}
}
You must tell react that your input is checked so that your CSS will apply it. selected ids must be kept in a place for future existence check. in the following code, I named this array selecetedIdx.
You also need to add idx on selection(via onChange event handler) or wrap them all in form and add them via extra dom attribute.
class Main extends Component {
// initialize selectedIdx with [] in your state (esp constructor)
// e.g. this.state = {/* rest of state, */ selectedIdx: []}
render() {
return (
{COLOR_LISTS.map((color, idx) => {
return (
// ...
<input
type="checkbox"
checked={selectedIdx.includes(idx)}
onChange={() => this.setState(state => ({
selectedIdx: [...state.selectedIdx, idx]
}))}
/>
// ...
)}
)
}
Your checkbox element needs name and value properties and would normally be a child of the <form> element.

React Carousel target div elements

I am learning to make custom Carousel by using React and Typescript. For styling I used styled components and scss. I found from one Article how to make Carousel. My carousel works fine.
I have made four div elements. when the carousel image slide will change, I want to change background-color of the div elements inot orange color. But Don't know how to do that.
I share my code in codesandbox
This is my Carousel component
import React, { useState, useEffect, useRef, memo, useCallback } from "react";
import styled from "styled-components";
interface ICarousel {
children: JSX.Element[];
currentSlide?: number;
autoPlay?: boolean;
dots?: boolean;
interval?: number;
arrow?: boolean;
}
const IMG_WIDTH = 320;
const IMG_HEIGHT = 700;
export default memo(
({
children,
autoPlay = false,
dots = false,
interval = 3000,
arrow = false
}: ICarousel) => {
const [currentSlide, setSlide] = useState(0);
const [isPlaying, setIsPlaying] = useState(autoPlay);
const timer = useRef<any>(undefined);
const slides = children.map((slide, index) => (
<CarouselSlide key={index}>{slide}</CarouselSlide>
));
const handleSlideChange = useCallback(
(index: number) =>
setSlide(
index > slides.length - 1 ? 0 : index < 0 ? slides.length - 1 : index
),
[slides]
);
const createInterval = useCallback(() => {
timer.current = setInterval(() => {
handleSlideChange(currentSlide + 1);
}, interval);
}, [interval, handleSlideChange, currentSlide]);
const destroyInterval = useCallback(() => {
clearInterval(timer.current);
}, []);
useEffect(() => {
if (autoPlay) {
createInterval();
return () => destroyInterval();
}
}, [autoPlay, createInterval, destroyInterval]);
return (
<CarouselContainer
onMouseEnter={() => {
if (autoPlay) {
destroyInterval();
}
}}
onMouseLeave={() => {
if (autoPlay) {
createInterval();
}
}}
>
<CarouselSlides currentSlide={currentSlide}>{slides}</CarouselSlides>
{arrow ? (
<div>
<LeftButton onClick={() => handleSlideChange(currentSlide - 1)}>
❮
</LeftButton>
<RightButton onClick={() => handleSlideChange(currentSlide + 1)}>
❯
</RightButton>
</div>
) : null}
{dots ? (
<Dots>
{slides.map((i, index) => (
<Dot
key={index}
onClick={() => handleSlideChange(index)}
active={currentSlide === index}
/>
))}
</Dots>
) : null}
</CarouselContainer>
);
}
);
const Buttons = styled.a`
cursor: pointer;
position: relative;
font-size: 18px;
transition: 0.6s ease;
user-select: none;
height: 50px;
width: 40px;
display: flex;
justify-content: center;
align-items: center;
align-content: center;
top: calc(50% - 25px);
position: absolute;
&:hover {
background-color: rgba(0, 0, 0, 0.8);
}
`;
const RightButton = styled(Buttons)`
border-radius: 3px 0 0 3px;
right: 0;
`;
const LeftButton = styled(Buttons)`
border-radius: 0px 3px 3px 0px;
left: 0;
`;
const Dots = styled.div`
display: flex;
justify-content: center;
align-items: center;
align-content: center;
margin-top: 10px;
`;
const Dot = styled.span<{ active: boolean }>`
cursor: pointer;
height: 15px;
width: 15px;
margin: 0 10px;
border-radius: 50%;
display: inline-block;
transition: background-color 0.6s ease;
background-color: ${({ active }) => (active ? `red` : `#eeeeee`)};
`;
const CarouselContainer = styled.div`
overflow: hidden;
position: relative;
width: ${IMG_WIDTH}px;
height: ${IMG_HEIGHT}px;
img {
/* change the margin and width to fit the phone mask */
width: ${IMG_WIDTH - 20}px;
height: ${IMG_HEIGHT - 50}px;
margin-left: 10px;
margin-top: 15px;
}
z-index: 1;
`;
const CarouselSlide = styled.div`
flex: 0 0 auto;
transition: all 0.5s ease;
width: 100%;
`;
const CarouselSlides = styled.div<{
currentSlide: ICarousel["currentSlide"];
}>`
display: flex;
${({ currentSlide }) =>
` transform: translateX(-${currentSlide ? currentSlide * 100 + `%` : 0})`};
transition: transform 300ms linear;
cursor: pointer;
`;
This where I am using the Carousel component
import * as React from "react";
import "./styles.scss";
import Carousel from "./carousel";
export const imgUrls = [
`https://images.unsplash.com/photo-1455849318743-b2233052fcff?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=900&q=60`,
`https://images.unsplash.com/photo-1508138221679-760a23a2285b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=900&q=60`,
`https://images.unsplash.com/photo-1519125323398-675f0ddb6308?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=900&q=60`,
`https://images.unsplash.com/photo-1494253109108-2e30c049369b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=900&q=60`
];
export default function App() {
return (
<div className="App">
<main className="Testeru">
<div className="phone-left">
// I want change background color of this div element
<div className="phone-left-upper">left upper</div>
<div className="phone-left-lower">left-lower</div>
</div>
<div className="phone-slider">
<div className="mobile_overlay">
<Carousel autoPlay>
{imgUrls.map((i) => {
return (
<img
key={i}
src={i}
alt=""
style={{
borderRadius: `20px`
}}
/>
);
})}
</Carousel>
</div>
</div>
// I want change background color of this div element
<div className="phone-right">
<div className="phone-right-upper">right upper</div>
<div className="phone-right-lower">right-lower</div>
</div>
</main>
</div>
);
}

Resources