Hide and show button in react - reactjs

I have one div element and inside it has one button A. and there is button B outside which is hidden by default
so when I click button A, the whole div should hide including button A, and also it should display the hidden button B.
And when I click button B, it should open the div and hide.
How can I achieve this in reactjs.
This is what I have tried, but it is not showing any button on the screen
import React from 'react'
import useState from 'react-dom'
const App = () => {
const [show,setShow]=useState(true)
return(
<>
{show && <div>
Hello
<button>button A</button>
</div>}
<button onClick={()=>setShow(!show)}>button 2</button>
</>
)

Take a look at how this code is setting and using the show boolean state value for Button A and Button B.
const { useState } = React;
const App = () => {
const [show, setShow] = useState(true)
return (
<div>
{show && <div>
Hello
<button onClick={()=>setShow(!show)}>Button A</button>
</div>}
{!show &&
<button onClick={()=>setShow(!show)}>
Button B
</button>
}
</div>
);
}
// Render it
ReactDOM.render(
<App />,
document.getElementById("root")
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>
Note: Make sure you're importing useState from 'react' in your code. I had to write it as const {useState} = React; in order to get the above code snippet to work as expected.

You can write something like below
import React, { useState } from "react";
export default function ToogelButton({ children }) {
// React state to manage visibility
const [showButtonB, setShowButtonB] = useState(false);
// function to toggle the boolean value
function toggleShow() {
setShowButtonB(showButtonB => !showButtonB);
}
if(showButtonB) {
return (
// Button B
<button onClick={toggleShow}>BUTTON B</button>
);
}
return (
// Button A and content
<div className="container">
Test Content
<button onClick={toggleShow}>BUTTON A</button>
</div>
);
}

Related

How to make a form shown when a button is clicked using a functional component in React?

cause when I search this, I only see codes in a class components.
also, how to show the same form n times depending on how many times the user clicked the button?
thank you in advance
edit: here's my initial code which i copied from someone's answer in another question. the problem is that whenever I click the button, it would show me the hidden part but it would only show for a second then refreshes the page and it's back to default where it is not shown.
import React, { useState, useEffect } from "react";
import './App.css';
import { Link } from 'react-router-dom';
import Axios from 'axios';
function Test() {
const [showForm, setShowForm] = useState(false);
const showForms = () => {
setShowForm(!showForm);
}
return (
<div>
<form>
<button onClick={showForms}>click me</button>
</form>
{showForm && (
<form>
<h1>hello</h1>
</form>
)}
</div>
)
}
export default Test;
const Main = () => {
const [showIt, setShowIt] = useState(true);
return (
<div>
{showIt ?
<div className={"visible"}></div>
:
<div className={"invisible"}></div>}
<button onClick={()=> setShowIt(!showIt)}>change state</button>
</div>
)
}

Why do createPortal renders the whole component?

I have a problem with the createPortal function. When I use the "Modal", then by changing the states, the whole "Modal" component will be rendered. Can you help me how to avoid this? So when I comment out the Modal wrap in the Cart component (as I did it below), it works as I expected, but with the Modal wrap, when the states are changed, not the component will be re-rendered, but always the whole Modal Component
Here is my Modal component with createPortal function:
import React from 'react';
import { createPortal } from 'react-dom';
import { useState } from 'react';
import './modal.scss';
export default function Modal({ children, onClick }) {
const BackDrop = () => {
return <div className='backdrop' onClick={onClick}></div>;
};
const Modal = () => {
return (
<div className='modal'>
<div className='content'>{children}</div>
</div>
);
};
return (
<>
{createPortal(<BackDrop />, document.getElementById('modal'))}
{createPortal(<Modal />, document.getElementById('modal'))}
</>
);
}
The Cart component which uses the Modal component:
import React, { useEffect } from 'react';
import Modal from '../UI/Modal';
import './cart.scss';
import { useCartContext } from '../../store/CartContext';
import CartItem from './CartItem';
export default function Cart({ onHideCart }) {
const { cart, totalPrice, updateTotalPrice, addToCartOne, removeFromCartOne } = useCartContext();
useEffect(() => {
updateTotalPrice();
}, [totalPrice, cart]);
const onAddHandler = (id) => {
addToCartOne(id);
updateTotalPrice();
};
const onRemoveHandler = (id) => {
removeFromCartOne(id);
updateTotalPrice();
};
return (
// <Modal onClick={onHideCart}>
<div>
<ul className='cart-items'>
{cart.map((item, idx) => (
<CartItem
key={item.id}
name={item.name}
price={item.price}
amount={item.amount}
onAdd={onAddHandler.bind(null, item.id)}
onRemove={onRemoveHandler.bind(null, item.id)}
/>
))}
</ul>
<div className='total'>
<span>Total Amount</span>
<span>$ {totalPrice.toFixed(2)}</span>
</div>
<div className='actions'>
<button className='button--alt' onClick={onHideCart}>
Close
</button>
<button className='button'>Order</button>
</div>
</div>
// </Modal>
);
}
So by changing the amount with + and - buttons, the html element with id modal, always renders, it's flashes in the devtools... but when I comment out the Modal wrap in the Cart component, there is no flashes by modal ID. I hope it makes sense.
The problem was with the two custom element inside of the Cart element. When I return
createPortal(
<>
<div className='backdrop' onClick={onClick}></div>
<div className='modal'>
<div className='content'>{children}</div>
</div>
</>,
document.getElementById('modal')
)
instead of this:
<>
{createPortal(<BackDrop />, document.getElementById('modal'))}
{createPortal(<Modal />, document.getElementById('modal'))}
</>
Then there is no problem with rendering.

Why the color doesn't change when the button is clicked?

Not sure why this is not working, when i click the buttons nothing changes?
I'm trying to create a login/signin page in ReactJs
Imports on page:
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Component:
import React from "react";
import Button from "./Button";
function Body() {
const [color, setColor] = React.useState("pink");
React.useEffect(() => {
document.body.style.background = color;
}, [color]);
function ChangeColor() {
setColor("red");
}
return (
<div className="Body">
<h3>Already have an account? </h3>
<Button content="Sign In" onClick={() => ChangeColor()} />
<h3>Don't have an account? </h3>
<Button content="Sign Up" onClick={() => ChangeColor()} />
</div>
);
}
export default Body;
You forgot to add onclick event to your Button component to which you pass the handler from the props.
import React from "react";
function Button({ content, onClick /* <- Here */ }) {
return <button onClick={onClick}>{content}</button>;
} // ^ HERE
export default Button;

How I can build dynamic button in reactjs

I'm new to react and I would like to build a dynamic button, I wrote this code but I don't know How I can pass text, style, and size to this button.
import "./button.css";
import React from "react";
const Button = ({
type,
onClick,
buttonStyle,
buttonSize,
}) => {
return (
<div>
<div>
<button
type={type}
onClick={onClick}
buttonStyle={buttonStyle}
buttonSize={buttonSize}
></button>
</div>
</div>
);
};
export default Button;
In React, html elements does not have buttonStyle and buttonSize attribute. The onClick attribute and the type attribute are valid.
You also need to pass in a props parameter in your Button Const Button(props) and add a style attribute which will contain your style declarations in key:value pair.
Also in order to be dynamic, your button should have a label. you can achieve this by adding props.buttonLabel
Your code should be similar to this code below:
import "./button.css";
import React from "react";
const Button = (props) => {
return(
<div>
<div>
<button
type={props.type}
onClick={props.onClick}
style={props.buttonStyle}
>
{props.buttonLabel}
</button>
</div>
</div>
);
};
export default Button;
I think I found the solution...
import "./button.css";
import React from "react";
const Button = ({ parentClassName, buttonLabel, type, onClick }) => {
return (
<div>
<div>
<button className={parentClassName} type={type} onClick={onClick}>
{buttonLabel}
</button>
</div>
</div>
);
};
export default Button;
ReactDOM.render(
<React.StrictMode>
<Button
type="button"
onClick={() => console.log("you clicked me")}
buttonLabel="Bye Now"
parentClassName="btn btn-secondary"
/>
</React.StrictMode>,
document.getElementById("root")
);
Blockquote

Why won't my history.push code for Button onClick handler work?

I've only been working with React.js for a month or so and I hope someone can point me towards my errors so I can learn more.
I've created a reusable button component, but during testing, while the button displays correctly and I can change the value correctly - the onClick function is not working. Right now, I am trying to get the button to redirect onClick to the first path.
Below I have added the relevant areas of my code and hope someone can assist.
Display component:
import Sidebar from '../../Components/SideNav/Sidebar'
import GenButton from '../../Components/Buttons/GenButton'
export default function Sales({ authorized }) {
let history = useHistory();
const handleRoute = () =>{
history.push("/")
}
if (!authorized) {
return <Redirect to='/' />
}
return (
<div>
<Sidebar />
<div className='content'>
<h2>Sales Page</h2>
<GenButton
value="Home"
onClick={handleRoute}
/>
</div>
</div>
)
}
GenButton code:
import React from 'react'
import './GenButton.css';
const GenButton = ({value, onClick}) => {
return <button className='btn' onClick={() => onClick}>
{value}
</button>
}
export default GenButton
I need to understand more about why this isn't working, as multiple components I need to create will have between 2-4 buttons that need to route towards other pages or events.
Thank you for your assistance.
Because onClick is a function inside your Gen Button component you need to call it as a function.
import React from 'react'
import './GenButton.css';
const GenButton = ({value, onClick = () => {}}) => {
return <button className='btn' onClick={() => onClick()}>
{value}
</button>
or just
import React from 'react'
import './GenButton.css';
const GenButton = ({value, onClick = () => {}}) => {
return <button className='btn' onClick={onClick}>
{value}
</button>
I added a default value to onClick too incase there isn't one on a particular button.

Resources