Switch Button using Hooks in ReactJS to display different content - javascript

I'm trying to create a switch button that can display 2 different contents depending on which of the 2 buttons I click on using the hooks in react js.
I would like to display for example a sentence "You have clicked on the left button" when I click on the left one and the opposite when I click on the right one.
I would like the content to be displayed just below the switch buttons.
In addition, I would like my button to remain active when I clicked on it. That is to say, it should be of a darker color since it is active.
Do you have an idea?
This is the piece of code :
import React,{useState} from 'react';
import {Button} from "react-bootstrap";
import {FontAwesomeIcon} from "#fortawesome/react-fontawesome";
import {faBars, faChartLine} from "#fortawesome/free-solid-svg-icons";
import CustomerTable from "../CustomerTable/CustomerTable";
export default function HookButtonSwitch(props) {
const [resultatContenu, setResultatContenu] = useState('Content initial');
const [state, setState] = useState(false);
const handleEventSwitchButton = event => {
let resultatContenu;
switch(event.target.id) {
case 'stats':
console.log("Coucou Stats");
resultatContenu = 'Stats';
break;
case 'list':
console.log("Coucou List");
resultatContenu = 'LIST';
break;
}
setResultatContenu(resultatContenu);
};
const toggle = () => setState(!state);
return (
<div>
<br />
<Button
id="list"
variant="light"
className="border-radius-left"
onClick={handleEventSwitchButton}
>
<FontAwesomeIcon icon={faBars} />
</Button>
<Button
id="stats"
variant="light"
className="border-radius-right"
onClick={handleEventSwitchButton}
>
<FontAwesomeIcon icon={faChartLine} />
</Button>
<div> {resultatContenu} </div>
{/* <p>-------</p>
<div onClick={toggle}>
<div className="toggle">
{state ? <div>Yes! 👍 </div> : <div>No! 👎</div>}
</div>
</div>
*/}
</div>
)
}
Thank you in advance.

check hope its work
import React,{useState} from 'react';
import {Button} from "react-bootstrap";
import {FontAwesomeIcon} from "#fortawesome/react-fontawesome";
import {faBars, faChartLine} from "#fortawesome/free-solid-svg-icons";
import CustomerTable from "../CustomerTable/CustomerTable";
export default function HookButtonSwitch(props) {
const [resultatContenu, setResultatContenu] = useState('Content initial');
const [state, setState] = useState(false);
const handleEventSwitchButton = (event,condition) => {
this.setState({buttonSwitch:condition})
let resultatContenu;
switch(event.target.id) {
case 'stats':
console.log("Coucou Stats");
resultatContenu = 'Stats';
break;
case 'list':
console.log("Coucou List");
resultatContenu = 'LIST';
break;
}
setResultatContenu(resultatContenu);
};
const toggle = () => setState(!state);
const {buttonSwitch=false}= this.state
return (
<div>
<br />
<Button
id="list"
variant="light"
className="border-radius-left"
style={buttonSwitch&&{backgroundColor:'black'}}
onClick={(e)=>handleEventSwitchButton(e,true)}
>
<FontAwesomeIcon icon={faBars} />
</Button>
<Button
id="stats"
variant="light"
className="border-radius-right"
style={!buttonSwitch&&{backgroundColor:'black'}}
onClick={(e)=>handleEventSwitchButton(e,false)}
>
<FontAwesomeIcon icon={faChartLine} />
</Button>
<div> {resultatContenu} </div>
{/* <p>-------</p>
<div onClick={toggle}>
<div className="toggle">
{state ? <div>Yes! 👍 </div> : <div>No! 👎</div>}
</div>
</div>
*/}
</div>
)
}

Related

Swapped useState to useSelector(redux) and it's not working anymore

build this part of the code with useState initially and everything worked perfectly but I need to share this state with my main component (no relationships between those two) and decided to use Redux but def something is wrong, any ideas?
Here's the console error:
MUI: The value provided to the Tabs component is invalid.
None of the Tabs' children match with "-1".
You can provide one of the following values: 0, 1, 2.
import { React } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import '../../css/SideBar.css';
import { UilSignOutAlt } from '#iconscout/react-unicons';
import Logo from '../../../../assets/img/companyLogo.jpg';
import { SidebarData } from '../../Data/Data';
import { setDashboard } from '../../../../app/actions';
function SideBar() {
const selected = useSelector((state) => state.dashboard);
const dispatch = useDispatch();
return (
<div className="Sidebar">
{/* logo */}
<div className="logo">
<img src={Logo} alt="logo" />
<span>Company Name</span>
</div>
{/* menu */}
<div className="menu">
{SidebarData.map((item, index) => (
/* eslint-disable */
<div
role='menu'
className={selected === index ? 'menuItem active' : 'menuItem'}
key={index}
onClick={() => dispatch(setDashboard(index))}
onKeyDown={() => dispatch(setDashboard(index))}
>
<item.icon />
<span>{item.heading}</span>
</div>
))}
<div className='menuItem'>
<UilSignOutAlt />
</div>
</div>
</div>
);
}
export default SideBar;

element manipulation in react

So I have a series of code where a button in the Header.jsx file that if clicked, it will display the content of the Notification.jsx file. The problem here is, I don't exactly know how can I display the content of Notification.jsx in index.js. I tried using conditional statements and is it possible to hide the h1 element once the button is clicked?
Header.jsx
import React from "react";
import { Button } from "#mui/material";
import { IconButton } from "#mui/material";
import NotificationsIcon from "#mui/icons-material/Notifications";
import SearchIcon from "#mui/icons-material/Search";
import Menu from "#mui/material/Menu";
import MenuItem from "#mui/material/MenuItem";
import FullNotifList from "./FullNotifList"
export default function Header() {
const [anchorEl, setAnchorEl] = React.useState(null);
const open = Boolean(anchorEl);
const handleClick = (event) => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
return (
<div>
<Button
id="basic-button"
aria-controls={open ? "basic-menu" : undefined}
aria-haspopup="true"
aria-expanded={open ? "true" : undefined}
onClick={handleClick}
>
<IconButton>
<NotificationsIcon />
</IconButton>
</Button>
<Menu
id="basic-menu"
anchorEl={anchorEl}
open={open}
onClose={handleClose}
MenuListProps={{
"aria-labelledby": "basic-button",
}}
>
{/* Button needs to be clicked in order to display Notification.jsx */}
<Button variant="contained">Notification Center</Button>
<MenuItem onClick={handleClose}>Profile</MenuItem>
<MenuItem onClick={handleClose}>My account</MenuItem>
<MenuItem onClick={handleClose}>Logout</MenuItem>
</Menu>
<IconButton>
<SearchIcon />
</IconButton>
</div>
);
}
Notification.jsx
import React from "react";
export default function Notification(){
return(
<div>
<ul>
<li> Hello </li>
<li> Hello </li>
<li> Hello </li>
<li> Hello </li>
</ul>
</div>
)
}
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import reportWebVitals from './reportWebVitals';
import Header from './Header'
import './index.css'
import Footer from './Footer';
import Notification from './Notification';
export default function Page(props) {
const [isClicked, setIsClicked] = React.useState(false)
function showHide(e) {
setIsClicked(true)
};
return(
<div className='main'>
<Header onClick={showHide}/>
{isClicked && <Notification />}
<h1> Sample body </h1>
<Footer />
</div>
)
}
ReactDOM.render(
<Page />,
document.getElementById('root')
);
Here is the sandbox link: https://codesandbox.io/s/friendly-darkness-9u5s22?file=/src/index.js
You just need to create a state property to handle if the element is visible or not (ex: showNotification ) defaulting to false:
const [showNotification, setShowNotification] = React.useState(false);
Then using the button click event to set it to true
<Button variant="contained" onClick={()=>{setShowNotification(true)}}>Notification Center</Button>
Then you implement conditional rendering by using the && operator inside JSX for the return, something like :
{showNotification && <Notification />}
The problem is that your Header component doesn't have prop onClick, so nothing is executing.

How to get a variable back from a called component

I have a problem: I have my main class Input.js. A user can select a photo and upload it. The problem is I want to check if the user uploaded a photo or not when he press the button. For example I can give from Profilepic.js to Pic.js the picture as props. But how could I get back a variable? For example I want to set the variable in Profilepic.js and when the user I pressing the button the method onClick() should executed. Inside of this method it should check which value the variable isPreview has. And if the User hasnt uploaded a picture there should be a lable signaling him that he has to upload an image to continue.
Input.js
import React, { useState, useEffect } from 'react';
import { InputTags } from 'react-bootstrap-tagsinput';
import 'react-bootstrap-tagsinput/dist/index.css';
import './Input.css';
import Profilepic from './Profilepic';
const Input = () => {
const checkAll = () => {
// Call Preview from Profilepic.js
}
return (
<div className="body-container">
<Profilepic></Profilepic>
<div className="row gutters">
<div className="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12">
<div className="text-right">
<button type="button" id="submit" name="submit" className="btn btn-primary" onClick={checkAll}>Speichern & Weiter <i class="fas fa-paper-plane"></i></button>
</div>
</div>
</div>
</div>
);
}
export default Input
Profilepic.js
import React, { useState } from "react";
import { Pic } from "./Pic.js";
const Profilpic = () => {
const [preview, setPreview] = useState(null);
const [isPreview, setIsPreview] = useState(false);
const fileSelectedHandler = (event) => {
try {
console.log(event.target.files[0]);
if (event.target.files[0].size > 70001680) {
alert("File is too big! Wie Samys Dick");
} else {
let img = URL.createObjectURL(event.target.files[0]);
setPreview(img);
setIsPreview(true);
}
}
catch (err) {
}
};
return (
<div>
{preview ? (
<div>
<label htmlFor="myInput">
<Pic preview={preview}></Pic>
</label>
<input
id="myInput"
style={{ display: "none" }}
type={"file"}
onChange={fileSelectedHandler}
/>
</div>
) : (
<div>
<label htmlFor="myInput">
<i className="fas fa-user-circle"></i>
</label>
<input
id="myInput"
style={{ display: "none" }}
type={"file"}
accept=".png,.jpg,.jpeg, .jfif"
onChange={fileSelectedHandler}
/>
</div>
)}
</div>
);
};
export default Profilpic;
Pic.js
import React from "react";
import "./Photo.css";
const STYLES = ["btn--primary", "btn--outline", "btn--test"];
const SIZES = ["btn--medium", "btn--large"];
export const Pic = ({ preview }) => {
//const checkButtonStyle = STYLES.includes(buttonStyle) ? buttonStyle : STYLES[0];
//const checkButtonSize = SIZES.includes(buttonSize) ? buttonSize : SIZES[0];
// Püsh for Samy
return (
<div class="profilepic">
<img
class="profilepic__image"
src={preview}
width="120"
height="120"
alt="Profibild"
/>
<div class="profilepic__content">
<span class="profilepic__icon">
<i class="fas fa-camera"></i>
</span>
<span class="profilepic__text">Profilbild ändern</span>
</div>
</div>
);
};
Description of the Problem
You can use the useImperativeHandle. This requires a bit of a wrapping of
Profilepic
import React, { forwardRef, useImperativeHandle, useState } from "react";
import { Pic } from "./Pic.js";
function Profilepic(props, ref) {
const [preview, setPreview] = useState(null);
const [isPreview, setIsPreview] = useState(false);
useImperativeHandle(
ref,
() => ({ isPreview }),
[isPreview]
);
...
return (
...
);
};
export default forwardRef(Profilepic);
Input
import React, { useState, useEffect, useRef } from 'react';
import Profilepic from './Profilepic';
const Input = () => {
const profilePicRef = useRef();
const checkAll = () => {
// access profilePicRef.current.isPreview
}
return (
<div className="body-container">
<Profilepic ref={profilePicRef} />
...
<button
type="button"
id="submit"
name="submit"
className="btn btn-primary"
onClick={checkAll}
>
Speichern & Weiter <i class="fas fa-paper-plane" />
</button>
...
</div>
);
}

How to change the button text on click

import React from "react";
function ToDoItem(props) {
function but(){
document.getElementById('testBtn').value='ok'
}
return (
<div
>
<li>{props.text} <button class="deletebtn" onClick={() => {
props.onChecked(props.id);
}}><span>Delete</span></button>
</li>
<hr/>
<input type="button" value="Test" id="testBtn" onclick={but}/>
</div>
);
}
export default ToDoItem;
I wrote this function to change the value of the id from from "Test" to "ok", but I donot know why it is not working. When I use onclick="but()" instead of onclick={but}, it says the function but() is unused. I am not why is this not working. Please help
This is how you do it in React. You dont mix react, with DOM manipulation:
import React, {useState} from "react";
function ToDoItem(props) {
const [buttonText, setButtonText] = useState('Test');
return (
<div>
<li>
{props.text}
<button
class="deletebtn"
onClick={() => {
props.onChecked(props.id);
}}
>
<span>Delete</span>
</button>
</li>
<hr />
<input
type="button"
value={buttonText}
id="testBtn"
onClick={() => setButtonText("Ok")}
/>
</div>
);
}
export default ToDoItem;
And an, update for follow-up question. With the styling it depends what kind of styling you use in your react application. But you could use inline styling to get the behaviour you want. I for one use styled components when working in React...here's an updated code.
import React, { useState } from "react";
function ToDoItem(props) {
const [buttonText, setButtonText] = useState("Test");
const [buttonColor, setButtonColor] = useState("red");
const changeButton = () => {
setButtonText(buttonText === "Test" ? "Ok" : "Test");
setButtonColor(buttonColor === "red" ? "blue" : "red");
};
return (
<div>
<li>
{props.text}
<button
class="deletebtn"
onClick={() => {
props.onChecked(props.id);
}}
>
<span>Delete</span>
</button>
</li>
<hr />
<input
style={{ backgroundColor: buttonColor }}
type="button"
value={buttonText}
id="testBtn"
onClick={changeButton}
/>
</div>
);
}
export default ToDoItem;
Adding to my comments, your code reimplemented with hooks.
import React, { useState } from "react";
function ToDoItem(props) {
const [value, setValue] = useState('Test');
function but(){
setValue('ok');
}
return (
<div>
<li>{props.text} <button class="deletebtn" onClick={() => {
props.onChecked(props.id);
}}><span>Delete</span></button>
</li>
<hr/>
<input type="button" value={value} id="testBtn" onclick={but}/>
</div>
);
}
export default ToDoItem;

How ReactJS display fetch response onClick

I am trying to generate a random user information when pressing the button, and display the information above the button. In ProfilePanel.js, I created a avatar and user constants, which will use to show the information. In index.js, the avatar constant works for that since it doesn't need to use the Button. however, for user constant, it doesn't work. In below's code, I am fetching a api data to display user name, but it didn't show anything, I am not sure where wrong, is something wrong in Button.js or index.js. and how can I fix it. Can somebody help me out? Thanks.
<Button title="name" >
<p key={contact.name} user={contact.name}></p>
</Button>
index.js
import React, { Component } from "react";
import ReactDOM from "react-dom";
import Panel from "./ProfilePanel";
import axios from 'axios';
import './index.css';
import Button from './Button';
const url = 'https://randomuser.me/api/';
class App extends Component {
constructor(props) {
super(props);
this.state = {
contacts: []
}
}
componentDidMount() {
this.fetchdata();
}
fetchdata() {
axios.get(url)
.then(res => {
console.log(res);
this.setState({ contacts: res.data.results});
});
}
render(){
const {contacts} = this.state;
return (
<div className="panel">
{contacts.map(contact => (
<div class="panel">
<Panel
key={contact.picture} avatar={contact.picture.medium}
/>
<li class="flex-container">
<Button title="name" >
<p key={contact.name} user={contact.name}></p>
</Button>
<Button title="location" onClick={this.fetchdata}>
</Button>
<Button key={contact.email} title="email">
</Button>
<Button key={contact.phone} title="phone">
</Button>
<Button key={contact.login.password} title="password">
</Button>
</li>
</div>
))}
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById("root")
);
ProfilePanel.js
import React, { Component } from "react";
import PropTypes from "prop-types";
import './index.css';
import Button from './Button';
const style={
borderRadius: 150,
margin: 15,
}
class Panel extends Component {
render() {
const { avatar, user } = this.props;
return (
<div className="Panel">
<div class="panels">
<div className="avatar">
<img src={avatar} class="imageStyle" alt="" width={"200%"} height={"auto"}/>
</div>
</div>
<div class="center">
<h2 className="user">{user}</h2>
</div>
</div>
);
}
}
export default Panel;
Button.js
import './index.css';
import React, { Component } from 'react';
class Button extends Component {
constructor(props) {
super(props);
this.state = {
open:false,
};
}
render() {
const { title } = this.props;
const {open} = this.state;
return (
<button className={` ${open ? 'open' : ''}`}
class='button' onClick={(e) => this.handleClick(e)}>
<div className="panel-heading">
<h2 class='buttoncenter'>{title}</h2>
</div>
</button>
);
}
handleClick(e) {
e.preventDefault();
this.setState({
open: this.state.open
})
}
}
export default Button;
You're not changing state in the handle click. You need to set open to true;
handleClick(e) {
e.preventDefault();
this.setState({
open: true
})
}
You need to pass your user information in index.js. I think you have missed to pass the user props to the panel component, so that it shows the avatar alone. Without passing the users props, you are trying to destructure there in panel component.
//index.js should be like this
render(){
const {contacts} = this.state;
return (
<div className="panel">
{contacts.map(contact => (
<div class="panel">
<Panel
key={contact.picture} user={contact.name} avatar={contact.picture.medium}
/>
<li class="flex-container">
<Button title="name" >
<p key={contact.name} user={contact.name}></p>
</Button>
<Button title="location" onClick={this.fetchdata}>
</Button>
<Button key={contact.email} title="email">
</Button>
<Button key={contact.phone} title="phone">
</Button>
<Button key={contact.login.password} title="password">
</Button>
</li>
</div>
))}
</div>
);
}

Categories