ReactJS How to toggle elements to hide or show - reactjs

I am very new to React and the ES6 syntax I have a chat widget that i want to toggle to show and hide as i click the header,and I have already implemented an onClick handler, but in terms of the logic I am having trouble finding a similar implementation online. this is my code:
import React, {Component} from 'react';
import chat from './styles.css';
import {connect} from 'react-redux';
class ChatWidget extends Component {
handleClick(event) {
console.log("Hide or unhide chat body")
}
render() {
return (
<div className={chat.container}>
<div onClick={this.handleClick.bind(this)}
className={chat.header}>
<span className={chat.name}>Idol</span>
</div>
<div className={chat.body}>
This is the Body of the chat
</div>
</div>
);
}
}
function mapStateToProps(state) {
return {
user: state.activeUser
};
}
export default connect(mapStateToProps)(ChatWidget);

It could look like this:
class ChatWidget extends Component {
constructor(props) {
super(props);
this.state = {
showChat: true
};
 }
handleClick(event) {
this.setState({
showChat: !this.state.showChat
});
}
render() {
return (
<div className={chat.container}>
<div onClick={this.handleClick.bind(this)}
className={chat.header}>
<span className={chat.name}>Idol</span>
</div>
{this.state.showChat &&
(<div className={chat.body}>
This is the Body of the chat
</div>)
}
</div>
);
}
}
function mapStateToProps(state) {
return {
user: state.activeUser
};
}
export default connect(mapStateToProps)(ChatWidget);
But there are different approaches for conditional rendering.
See documentation here: https://facebook.github.io/react/docs/conditional-rendering.html

Use a state variable that will store the current state, whether to show the body or not. On the basis of that variable render the body of the Chart, that is called conditional rendering.
Check this:
class ChatWidget extends Component {
constructor(){
super();
this.state={isShowBody: true}
}
handleClick(event) {
this.setState({isShowBody: !this.state.isShowBody})
}
render() {
return (
<div className={chat.container}>
<div onClick={this.handleClick.bind(this)} className={chat.header}>
<span className={chat.name}>Idol</span>
</div>
{this.state.isShowBody ?
<div className={chat.body}>
This is the Body of the chat
</div>
: null}
</div>
);
}
}

What you can do is create a css class
.hidden {
display: none;
}
And dynamically toggle that class on your <div class={chat.body}.
So add an id to the div so it's easier to grab.
<div class={chat.body} id='chat-body'>
...
</div>
And inside your handleClick method
handleClick(event) {
let chat = document.getElementById("chat-body");
chat-body.classList.toggle('hidden')
}

Here you have an example, it has comments on the lines so you know what each line is doing.
Consider that adding a hidden class to the component will not unmount it, it will just hide it from the DOM
import React, {Component} from 'react';
import chat from './styles.css';
import {connect} from 'react-redux';
class ChatWidget extends Component {
// You need state to update the view
state = {
show: false
}
toggleBody() {
// You can pass true or false to this function to show or hide the body
this.setState({show: !this.state.show})
}
render() {
{/* Take the show property from the state */}
const {show} = this.state
return (
<div className={chat.container}>
<div onClick={this.toggleBody.bind(this)} className={chat.header}>
<span className={chat.name}>Idol</span>
</div>
{/* Add the class hidden to the body if show is false (you should create the hidden class in CSS) */}
<div className={`${chat.body} ${show ? '' : 'hidden'}`}>
This is the Body of the chat
</div>
</div>
);
}
}
function mapStateToProps(state) {
return {
user: state.activeUser
};
}
export default connect(mapStateToProps)(ChatWidget);

Related

How to render a YouTube video upon button click in React?

I am new to React and am trying to build a video player page. Currently I have a super basic page in mind — I'd like to have one button that, when clicked, renders a YouTube video.
I've followed a resource that uses the npm react-player package so that I can just embed a Youtube Player as follows:
function YouTubePlayer () {
return (
<div>
<ReactPlayer
url="https://www.youtube.com/watch?v=ug50zmP9I7s"
/>
</div>
)
}
export default YouTubePlayer
However, instead of having the video display on the page as soon as it loads, I want it to only load when the button is clicked. I created a button and an event handler like this:
import { Component } from 'react';
import ReactPlayer from 'react-player';
class YouTubePlayer extends Component {
constructor(props) {
super(props);
}
handleYouTubeClick = () => {
return (
<div>
<ReactPlayer url="https://youtu.be/OXHCt8Ym9gw"/>
</div>
);
}
render() {
return (
<div>
<p>Video Player</p>
<button onClick={this.handleYouTubeClick}>YouTube</button>
</div>
);
}
export default YouTubePlayer
but no video gets rendered. Do I have to do something with states? I do not know how I would go about doing so. Again, I am very new to React, so please let me know if I am approaching this completely wrong. Thanks.
import { Component } from "react";
import ReactPlayer from "react-player";
class YouTubePlayer extends Component {
constructor(props) {
super(props);
this.state = {
isClicked: false
};
}
handleYouTubeClick = () => {
this.setState({
isClicked: true
});
};
render() {
return (
<div>
<p>Video Player</p>
<button onClick={this.handleYouTubeClick}>Youtube</button>
{this.state.isClicked && (
<div>
<ReactPlayer url="https://youtu.be/OXHCt8Ym9gw" />
</div>
)}
</div>
);
}
}
export default YouTubePlayer;
Here is the code to solve your problem.
class YouTubePlayer extends Component {
state = {
showYoutube: false,
}
ShowPlayer = () => {
if(this.state.showYoutube) {
return (
<div>
<ReactPlayer url="https://youtu.be/OXHCt8Ym9gw"/>
</div>
);
}
}
handleYouTubeClick = () => {
this.setState({
showYoutube: true,
})
}
render() {
return (
<div>
<p>Video Player</p>
<this.ShowPlayer />
<button onClick={this.handleYouTubeClick}>Youtube</button>
</div>
);
}
}
I hope this will help you.
Thanks

How to get data in class A from class B in reactjs

Here I added two Classes and want to get data from one class to another class but I am getting errors like this "Warning: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it."
import React, { Component } from 'react';
import DataHtml from "../datahtml";
export default class AllData extends Component {
render(){
return (
<div className="row g-6 g-xl-9">
<DataHtml />
</div>
);
}
}
import React, { Component } from 'react';
class DataHtml extends Component {
constructor(props) {
super(props)
this.state = {
data: [ {"name": "demo","date": "02-02-2022"},{"name": "demo","date": "02-02-2022"}]
}
}
DataHtmlStructure = () => {
this.state.data.map((data) => {
return (
<div className="col-md-6 col-xl-4 test-card">
<div className="card-body p-9 pt-4">
<div className="fs-3 fw-bolder text-dark mb-1">{data.name}</div>
<div className="fs-5 text-gray-600">
<i className="bi bi-calendar-date-fill"></i>{data.date}
</div>
</div>
</div>
);
})
}
render() {
return this.DataHtmlStructure;
}
}
export default DataHtml;
You need to invoke your function in your render method.
render() {
return this.DataHtmlStructure();
}

How can I tried to render forms to this MainScreen.js file when the user click on in the navbar?

The main form page where the login and Sign up form will live give undefined. How can I tried to render forms to this MainScreen.js file when the user click on in the navbar.
MainScreen.js (Where the forms are live)
import React from 'react';
import RegisterBox from '../Forms/Register'
import LoginBox from '../Forms/Login'
// This is the page for form to live on
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoginOpen: true,
isRegisterOpen: false
};
}
render() {
return (
<div>
<div className="root-container">
{this.state.isLoginOpen && <LoginBox/>}
{this.state.isRegisterOpen && <RegisterBox/>}
</div>
</div>
)
}
}
export default App;
Navigation.js (Where the button is clicked but are not being defined anywhere so cannot find the page to take me to the forms.)
import React from 'react';
import { BrowserRouter as Router, Link } from 'react-router-dom';
import Dropdown from "../components//pages/dropdowns/dropdowns";
import hamburger from "../images/menu.svg"
class Navigation extends React.Component {
constructor(props) {
super(props);
this.state = {
isExpanded: false
};
}
handleToggle(e) {
e.preventDefault();
this.setState(prevState => ({
isExpanded: !prevState.isExpanded, // negate the previous expanded state
}));
}
render() {
const { isExpanded } = this.state;
return (
<Router>
<div className="NavbarContainer">
<div className="mobilecontainer LeftNav">
<h2 className="BrandName LeftNav mobileboxmenu inline FarRight">Kommonplaces</h2>
<div className="hamburger inlinev" >
<img
onClick={e => this.handleToggle(e)}
alt="menubtn"
src={hamburger}
/>
</div>
</div>
<ul className={`NavBar collapsed ${isExpanded ? "is-expanded" : ""}`}>
<Dropdown/>
<li className="RightNav"><Link to="/">Host Your Space</Link></li>
<li className="RightNav"><Link to="/">About Us</Link></li>
<li className="RightNav"><Link to="/">Contact Us</Link></li>
<div className="btnflexright">
<button
className={"controller " + (this.state.isLoginOpen
? "selected-controller"
: "")}
onClick={this
.props
.showLoginBox}>
Login
</button>
<button
className={"controller " + (this.state.isRegisterOpen
? "selected-controller"
: "")}
onClick={this
.props
.showRegisterBox}>
Sign up
</button>
</div>
</ul>
</div>
</Router>
);
}
}
export default Navigation;
You need to do a couple things:
add some couple methods to your App component to set the state.
import and render the Navigation component in your App component (so you can pass your methods in as functions. you could use the Context API but it's more complicated...)
pass those methods as functions to your Navigation component (and pass the state in as props if you need them too)
call the methods through the props of your Navigation component
In your App component:
import React from 'react';
import RegisterBox from '../Forms/Register'
import LoginBox from '../Forms/Login'
import Navigation from './Navigation'
// This is the page for form to live on
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoginOpen: true,
isRegisterOpen: false
};
}
/*
* 1. add these two methods here to modify the state of `App`
*/
showLoginBox() {
this.setState({ isLoginOpen: true });
}
showRegisterBox() {
this.setState({ isRegisterOpen: true });
}
render() {
return (
<div>
<div className="root-container">
{
/* 2. render the `Navigation` component in `App` */
/* 3. pass your methods in as function props to `Navigation` */
}
<Navigation
isLoginOpen={this.state.isLoginOpen}
isRegisterOpen={this.state.isRegisterOpen}
showLoginBox={this.showLoginBox.bind(this)}
showRegisterBox={this.showRegisterBox.bind(this)}
/>
{this.state.isLoginOpen && <LoginBox/>}
{this.state.isRegisterOpen && <RegisterBox/>}
</div>
</div>
)
}
}
export default App;
Now you can call those methods from your Navigation component...
{ /* 4. call the prop functions in `Navigation` component */ }
<button
className={"controller " + (this.props.isLoginOpen ? "selected-controller" : "")}
onClick={this.props.showLoginBox}>
Login
</button>
<button
className={"controller " + (this.props.isRegisterOpen ? "selected-controller" : "")}
onClick={this.props.showRegisterBox}>
Sign up
</button>

Passing method child's component to another 'external' component in ReactJS

I'm new to ReactJs, coding and this is my first time posting here! So, I'm trying to build a Todo app in ReactJs. I have four components.
the first compo. is App.js - the parent one
import React, { Component } from 'react';
import TaskTodo from './TaskTodo';
import './App.css';
import TaskDisplayed from "./TaskDisplayed";
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">Hey, i'm the header! </h1>
</header>
<div className="App-intro">
<TaskTodo/>
</div>
<div className="App-right">
<TaskDisplayed/>
</div>
</div>
);
}
}
export default App;
TaskTodo.js - which is the parent of the TodoItems.js
import React, {Component} from 'react';
import TodoItems from './TodoItems';
export default class TaskTodo extends Component{
constructor(props) {
super(props);
this.state = {
items: []
};
this.addItem = this.addItem.bind(this);
};
addItem(e) {
const itemArray = this.state.items;
if (this._inputElement.value !== "") {
itemArray.unshift(
{
text: this._inputElement.value,
key: Date.now()
}
);
this.setState({
items: itemArray
});
this._inputElement.value = "";
}
e.preventDefault();
}
render() {
return (
<div className="todoListMain">
<div className="header">
<form onSubmit={this.addItem}>
<input type="text" ref={(a) => this._inputElement = a}
placeholder="Add a list">
</input>
</form>
</div>
<TodoItems entries={this.state.items}/>
</div>
);
}
}
TodoItems.js - the child of the TaskTodo.js
import React, { Component } from 'react';
class TodoItems extends Component {
constructor(props) {
super(props);
this.createTasks = this.createTasks.bind(this);
}
handleClick = (text) => {
console.log(text);
}
createTasks(item) {
return <li key={item.key}><a onClick={() => this.handleClick(item.key, item.text)} href={'#about'}>#{item.text}</a></li>
}
render() {
const todoEntries = this.props.entries;
const listItems = todoEntries.map(this.createTasks);
return (
<ul className="theList">
{listItems}
</ul>
);
}
};
export default TodoItems;
What I need to do, is how I can pass the handleClick method (a child's of TaskTodo) to an 'external' component - TaskDisplayed.js; or how I can track when the user click to a listed item? Please pardon me for this unprofessional way of asking! But, I truly need to get in track with ReactJS! Thanks!
p.s. The above code I found online, so thanks for that :D!
You should define the onClick event handler in the parent component and pass it to the child as a prop.
See How to pass an event handler to a child component in React
In this case, you would want to define it in the App component since that is the parent of the two components that need to communicate.

Communicating between independent components react

I have been facing a problem, I would like to write a div every time a specific button is clicked, but the button is in one component and the menu in which I want the div to be created is in another component as well , and both main components are in one component, is there a way of making this happen? So the structure of it all is something like this:
This is the root component with the smaller components in it:
export class Root extends React.Component {
render() {
return(
<div className="Body">
<div id="SideBar" ><SideMenu/></div>
<MenuCocktails/>
<MenuBeers/>
<MenuVines/>
<MenuLemonades/>
<MenuSoftDrinks/>
<MenuCollection/>
<MenuCharger/>
<div id="BottomMenu"><BottomMenu/></div>
</div>
)
}
}
this is the menu that I wanted to div to be created in:
export class BottomMenu extends React.Component{
constructor() {
super();
this.state = {
shown: ''
};
}
toggleMenu = () => {
this.setState({shown: this.state.shown ? '' : 'visible'});
}
render() {
return(
<div>
<button
id="button"
className={this.state.shown}
onClick={this.toggleMenu}
>
My Cart
</button>
<div id="Header" className={this.state.shown}>
<button id="CheckOutButton">Check Out</button>
</div>
</div>
);
}
}
and this is one of the components with the button:
import React from "react";
import styles from "./MenuCocktails.css";
import plus from "./plus.png";
export class NiğdeGazozu extends React.Component{
render() {
return (
<div id="menu-items-1">
<div id="item-name">NIĞDE GAZOZU</div>
<div id ="price-item">8 TL</div>
<button id="plusbutton"><img src={plus}/></button>
</div>
);
}
}

Resources