In react-js I have two div and two button, 1st button click fist div show and second button click second div show and 1st div hide
export default function Provider() {
let firstClick = () => {
const itemList = document.querySelector(".firstdiv");
const itemList2 = document.querySelector(".Seconddiv");
itemList.style.display = "block";
itemList2.style.display = "none";
}
let secondClick = () => {
const itemList = document.querySelector(".firstdiv");
const itemList2 = document.querySelector(".Seconddiv");
itemList.style.display = "none";
itemList2.style.display = "block";
}
return (
<div className="firstdiv">First Div Content</div>
<div className="Seconddiv">Second Div Content</div>
<button onClick={firstClick}>First Button</button>
<button onClick={secondClick}>Second Button</button>
})
I use this method is use in react how to rewrite the code in react way, I am new in react and thanks in advance
Using React you would go about this a bit different:
instead of hiding components by css, you would render or not render components.
A compact example:
const SomeDiv = () => {
const [showFirst, setShowFirst] = useState(true);
// sets showFirst to not the value of showFirst and triggers a render
const toggle = () => setShowFirst(!showFirst);
return showFirst
? <button onClick={toggle}>First</button>
: <button onClick={toggle}>Second</button>
}
You can do something like that:
import { useState } from "react";
export default function HealthcareProvider() {
const [hide, setHide] = useState(false);
const toggleHide = () => {
setHide(!hide);
};
return (
<div>
<div className="firstdiv"
style={{ display: hide ? "block" : "none" }}>
First Div Content
</div>
<div className="Seconddiv" style={{ display: hide ? "none" : "block" }}>
Second Div Content
</div>
<button onClick={toggleHide}>First Button</button>
<button onClick={toggleHide}>Second Button</button>
</div>
);
}
Related
Here is my App()
import React, { useState, useEffect } from "react";
import { useParams } from "react-router";
const ComponentTest = () => {
const { _sid } = useParams();
const [sid, setsid] = useState(_sid);
const [myData, setmyData] = useState({
message: "",
file: "",
createTime: "",
});
const onClick = async () => {
const resopnse = await fetch("http://127.0.0.1:5100/api/get?_sid=" + sid);
const resopnseJson = await resopnse.json();
setmyData({
...myData,
message: resopnseJson.message,
file: resopnseJson.file,
});
};
return (
<div>
<button
className="btn btn-outline-primary form-control"
data-bs-toggle="modal"
data-bs-target="#myModal"
onClick={onClick}
>
Test
</button>
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">...</div>
</div>
</div>
</div>
);
};
The problem is when the button is clicked, the modal appears then data is loaded.
What I want is: First fetch data, then show up the modal.
Do I need to use useEffect? and how? Thanks!
Any good ways to learn hooks?
The first issue which needs to be resolved is the modal showing up without a condition. So go ahead and wrap the modal container div with a condition which will always render the modal (will change this in later):
const YourComponent = () => {
....
return (
<div>
<button>Test</button>
{true === true ? <div class="modal" id="myModal">...</div> : null}
</div>
)
}
This way, you are not just rendering the modal, you are also controlling its render. Next you have to figure out a way to set the value of the condition placeholder (true === true). This can be done with state, but looking at your code, I think that it is easier and more efficient to add a flag in your data state and set it to true whenever you get a response. Then use that flag to see if the modal should or should not render:
const ComponentTest = () => {
const { _sid } = useParams();
const [sid, setsid] = useState(_sid);
const [myData, setmyData] = useState({
message: "",
file: "",
createTime: "",
loaded: false
});
const onClick = async () => {
const resopnse = await fetch("http://127.0.0.1:5100/api/get?_sid=" + sid)
const resopnseJson = await resopnse.json();
setmyData(
{ ...myData, message: resopnseJson.message, file: resopnseJson.file, loaded: true }
)
}
return (
<div>
<button className="btn btn-outline-primary form-control" data-bs-toggle="modal" data-bs-target="#myModal" onClick={onClick}>Test</button>
{myData.loaded === true ? <div class="modal" id="myModal">...</div> : null}
</div>
)
}
const [showModal,setShowModal] = useState(false);
when you click on the button to fetch data you set showModal to true
const onClick = async () => {
//...
setShowModal(true); // add this line
}
Now in your jsx you check if showModal is true so you display it :
return(
//...
{showModal ? (
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">...</div>
</div>
</div>
) : ''}
);
don't forget to create a button in your modal to close it
<button
onClick={() => {
setShowModal(false);
}}>
Close Modal
</button>
How to add or remove css classes from an element in react functional component?
setup:
export default function App() {
const menuOptions = ["home", "blog", "feedback"];
const [classes, setClasses] = useState("btn btn-secondary m-1");
const [activeIndex, setActiveIndex] = useState(0);
generate menu buttons:
const renderMenu = menuOptions.map((menuItem, indx) => {
return (
<button
key={indx}
className={classes}
onClick={(key) => handleClick(key)}
>
{menuItem}
</button>
);
});
rendering:
return (
<div className="App">
<h1>Add Remove CSS classes</h1>
{renderMenu}
</div>
);
}
I have just started learning React so I am struggling with adding/removing classes.
sample code: https://codesandbox.io/s/tender-poincare-qw64m0?file=/src/App.js
I am trying to make a Modal component. I would like that when the modal appears, it appears with a transition just like when it disappears. This is currently very jerky, why and how can I fix it?
I would like that when the modal is shown it is shown with an animation and the same behavior when the modal disappears (click on the button).
thank you very much for the help, I know I will learn a lot.
//content of styles.css
.modal {
position: absolute;
width: 100%;
height: 100%;
background: red;
transition: all 300ms ease-out;
transform: translateY(100%);
}
.show {
transform: translateY(0%);
}
.hide {
transform: translateY(100%);
}
app.js
import Modal from "./modal";
/*
const Modal = ({ show, children }) => {
return <div className={`modal ${show ? "show" : "hide"}`}>.
{children} </div>;
};
export default Modal;
*/
import ModalContent from "./modalContent";
/*
const ModalContent = ({ show }) => {
const showModal = () => {
show();
};
return <button onClick={showModal}> close modal</button>;
};
export default ModalContent;
*/
export default function App() {
const [show, setShow] = useState(false);
const closeModal = () => {
setShow(false);
};
useEffect(() => setShow(true), []);
return (
<div className="App">
{show && (
<Modal show={show}>
<ModalContent show={closeModal} />
</Modal>
)}
</div>
);
}
I updated my code:
this is my live code
First of all, in your demo modal disappears immediately, without any transition. It seems, that it's cause by re-rendering of whole App component, on show state change. Extracting Modal component out of App do the trick for me:
const Modal = ({ show, children }) => {
useEffect(() => {}, [show]);
return <div className={`modal ${show ? "show" : "hide"}`}>{children} </div>;
};
export default function App() {
Second point - you can't control initial setup just with with css transition. Transition appears when something (class, attribute, pseudoclass) changes on the given element. To get around this and have smooth modal appearance, you can setup one-time useEffect in the App component, which will change show state from false to true. My overall snippet:
const Modal = ({ show, children }) => {
return <div className={`modal ${show ? "show" : "hide"}`}>{children} </div>;
};
export default function App() {
const ModalContent = ({ show }) => {
const showModal = () => {
show();
};
return <button onClick={showModal}> close modal</button>;
};
const [show, setShow] = useState(false);
const closeModal = () => {
setShow(false);
};
useEffect(() => setShow(true), [])
return (
<div className="App">
<Modal show={show}>
<ModalContent show={closeModal} />
</Modal>
</div>
);
}
I have a list of div elements in a ReactJS projects. I want to just get an indication when someone clicks change the background color.
the following is the basic code.
function changetoselected(event){
// now change backgroundColor of
// event.currentTarget to white
}
<div>
bigarrayofsize100plus.map((item,index) =>{
return(
<div
className="p-2"
onClick={(e) => changetoselected(e)}
style={{backgroundColor:"green"}}
>
.....
</div>
)
}
</div>
I dont want to store in the state all the elemets uncessarily. I dont have to trace clicked items here.
If once clicks i want to just change color. How can i do it
Use the style property to set a backgroundColor like this.
function changetoSelected(event){
event.target.style.backgroundColor = '#fff'
}
You can also use Refs in React like this
For a Function Component do this
`
import { useRef } from 'react';
function MyComponent() {
const divEl = useRef(null);
const changeToSelected = () => {
divEl.current.style.backgroundColor = '#fff';
};
return (
<div ref={divEl} onClick={changeToSelected}>
...
</div>
);
}
For a Class Component do this
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.divElement = React.createRef();
}
changetoselected = () => {
this.divElement.current.style.backgroundColor = '#fff';
}
render() {
return <div ref={this.divElement} onClick={this.changetoselected}>
...
</div>;
}
}
After all, working with pure dom (by ref or event) may not be what you are searching for, you can consider using react state and apply className or style to your dom elements
import { useState } from 'react';
const MyComponent = () => {
const [backgroundColor, setBackgroundColor] = useState('green');
return (
<div
onClick={() => setBackgroundColor('white')}
style={{ backgroundColor }}
>
...
</div>
);
}
EDIT
function MyComponent() {
const divEl = useRef(null);
const changeToSelected = () => {
divEl.current.style.backgroundColor = '#fff';
};
return (
<div>
{bigarrayofsize100plus.map((item,index) =>
<ChildComp
key={index}
item={item}
>
.....
</div>
)}
</div>
);
}
function ChildComp({ item }) {
const divEl = useRef(null);
const changeToSelected = () => {
divEl.current.style.backgroundColor = '#fff';
};
return (
<div
ref={divEl}
onClick={changeToSelected}
className="p-2"
style={{backgroundColor:"green"}}
>
// do stuff with item heere
</div>
);
}
i want to display a dialog to the bottom right corner of the page on clickin a button using react and typescript.
There is a button named "Add" in ListComponent. when clicking that button dialog which is the DialogComponent should be rendered.
Below is how the ListComponent and DialogComponent looks
function ListComponent() {
const onAddClicked = () => {
//what to be done
}
return (
<button onClick={onAddClicked}> Add</button>
);
}
function DialogComponent() {
return (
<Wrapper> Dialog </Wrapper>
)
}
Now i cannot call DailogComponent within ListComponent as it would push the layout of the page.
So i want to call this DailogComponent within MainComponent which is something like below
function Main () {
return (
<ListComponent>
//some props
</ListComponent>
)
}
I am new to using react with typescript. How can i do this. could someone provide some insights into this. thanks.
You will likely want to use fixed positioning (and possibly some increased z-index, if necessary) to display a dialog box at the bottom right of the screen. This will "break" it out of being rendered "inline" with your content.
At a minimum you should utilize the following CSS rules
position: fixed;
bottom: <M>; // M units from the bottom
right: <N>; // N units from the right
The linked codesandbox sets this Dialog class style and component
CSS
.dialog {
position: fixed;
bottom: 1rem;
right: 1rem;
padding: 1rem;
border-radius: 5px;
background-color: lightblue;
}
JSX
const Dialog = ({ showDialog, text }) =>
showDialog ? <div className="dialog">{text}</div> : null;
How you toggle the display state of the dialog is up to you.
EDIT: Full code with a demo ListComponent
const Dialog = ({ showDialog, text }) =>
showDialog ? <div className="dialog">{text}</div> : null;
const ListComponent = ({ data, toggleDialog }) =>
data.map((el, i) => (
<div key={i}>
<button type="button" onClick={toggleDialog}>
{el}
</button>
</div>
));
export default function App() {
const [showDialog, setShowDialog] = useState();
const toggleDialog = () => setShowDialog(s => !s);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<button type="button" onClick={toggleDialog}>
Toggle Dialog in Main
</button>
<h2>List Component</h2>
<ListComponent data={["A", "B", "C"]} toggleDialog={toggleDialog} />
<Dialog showDialog={showDialog} text="I'm a dialog" />
</div>
);
}
This is essentially applying Lifted State. State and mutators are lifted to a common ancestor of components interested in either displaying the state, or updating. State and state updaters are passed as props to children.
You need to have a callback in order to display the dialog box from Main function.
Below is an example:
import React, { useState } from "react";
import { render } from "react-dom";
import Modal from "react-modal";
const Main = () => {
const [isOpen, setIsOpen] = useState(false);
const handleAddClick = () => {
setIsOpen(true);
};
return (
<React.Fragment>
<ListComponent onAddClickedProps={handleAddClick} />
<DialogComponent isOpen={isOpen} />
</React.Fragment>
);
};
const ListComponent = ({ onAddClickedProps }) => {
const onAddClicked = () => {
onAddClickedProps();
};
return <button onClick={onAddClicked}> Add</button>;
};
const DialogComponent = ({ isOpen }) => {
return (
<Modal isOpen={isOpen}>
<div>I am a modal</div>
</Modal>
);
};
render(<Main />, document.getElementById("root"));
React-modal-example-on-sandbox