react js onClick toggle class on different elements inside different components - javascript

i am fairly new to react and i am building an app that has 2 languages. you can switch between the languages from the navbar using Redux to handle the state. i have a json file where i stored the text for both languages and used onClick to switch between them. it works great on every component and every page.
however my problem is on some components where i am using map() and find() functions to get data from a different json file so i feel like i am forced to find another solution to switch languagse on these components and the simplest solution i could think of is to hide/show a class between two h1 for example one for english and one for arabic.
how can i make an onClick function on the navbar button that will change the language and also show/hide a class on other components not a child component in order to show one of the two languages?
this is the Navbar.js
import React, { Component } from 'react';
import { bubble as Menu } from 'react-burger-menu'
import { NavLink } from 'react-router-dom'
import './Navbar.css';
import '../../../data/content.json'
const Provider = require('react-redux').Provider;
const createStore = require('redux').createStore;
const content = require('../../../reducer');
class Navbar extends Component {
showSettings (event) {
event.preventDefault();
}
render() {
const data = this.props.data;
let switchLanguage = this.props.switchLanguage;
return (
<div>
<ul className="right hide-on-med-and-down language">
<li className="dropdown-button right"><a onClick={switchLanguage.bind(this,'en')} className="language-a">Eng</a></li>
<li className="dropdown-button right"><a onClick={switchLanguage.bind(this,'ar')} className="language-a">عربي</a></li>
<li className="right">
<p>CALL US: +905061162526</p>
</li>
</ul>
<i onClick={ this.showSettings } className="material-icons sidenav-trigger right">menu</i>
<Menu >
<img className="sidenav-logo" src="https://res.cloudinary.com/dd5e5iszi/image/upload/v1522222933/other/home-page-logo.png" alt="cayan group logo"/>
<li className="link-wrapper">
<NavLink activeClassName="selected" className="menu-item" exact to="/">{data.home}</NavLink>
</li>
<li className="link-wrapper">
<NavLink activeClassName="selected" className="menu-item" exact to="/projects">{data.projects}</NavLink>
</li>
<li className="link-wrapper">
<NavLink activeClassName="selected" className="menu-item" exact to="/services">{data.services}</NavLink>
</li>
<li className="link-wrapper">
<NavLink activeClassName="selected" className="menu-item" exact to="/about">{data.about}</NavLink>
</li>
<li className="link-wrapper">
<NavLink activeClassName="selected" className="menu-item" exact to="/contact">{data.contact}</NavLink>
</li>
</Menu>
<div className="navbar-fixed">
<nav className="normal-nav">
<div className="nav-wrapper">
<img className="responsive-img" src="https://res.cloudinary.com/dd5e5iszi/image/upload/v1522221061/other/logo-nav.png" alt="cayan group logo"/>
<ul className="nav-links center hide-on-med-and-down">
<li className="link-wrapper">
<NavLink activeClassName="selected" className="nav-link" exact to="/">{data.home}</NavLink>
</li>
<li className="link-wrapper">
<NavLink activeClassName="selected" className="nav-link" to="/projects">{data.projects}</NavLink>
</li>
<li className="link-wrapper">
<NavLink activeClassName="selected" className="nav-link" to="/services">{data.services}</NavLink>
</li>
<li className="link-wrapper">
<NavLink activeClassName="selected" className="nav-link" to="/about">{data.about}</NavLink>
</li>
<li className="link-wrapper">
<NavLink activeClassName="selected" className="nav-link" to="/contact">{data.contact}</NavLink>
</li>
</ul>
</div>
</nav>
</div>
</div>
);
}
}
export default Navbar;
this is the where i want to hide/show a class. on some tags in want to show and hide one of them based on the language selected
import React, { Component } from 'react';
import Slider from 'react-slick';
import PRODUCTS from '../../Data/CarouselData.js';
import './ProjectsCarousel.css';
class ProjectsCarousel extends Component {
render() {
const data = this.props.data;
var settings = {
dots: false,
infinite: true,
speed: 500,
slidesToShow: 3,
slidesToScroll: 1,
adaptiveHeight: true,
autoplay: false,
autoplaySpeed: 5000,
responsive:[
{ breakpoint: 400, settings: { slidesToShow: 1 } },
{ breakpoint: 1024, settings: { slidesToShow: 2 } }
]
};
return (
<div className="projetcsCarousel ">
<div className="containermy">
<div className="row">
<div className="container">
<h1 className="body-h1">PROJECTS</h1>
</div>
<div className="carousel">
<div className="left-btn col s1">
<p>PREV</p>
</div>
<Slider className="inner col s10" {...settings}>
{PRODUCTS.map((product)=>{
return (
<a key={product.id} href={'/products/'+product.id}>
<div className='wrapper'>
<div className={'carouselImages cayan-'+product.id}>
<h6>{'CAYAN'+product.id}</h6>
</div>
<div className="description">
<h6>Description</h6>
<h5>{product.priceMin + ' - ' + product.priceMax}</h5>
<p>{product.description}</p>
<p>{product.descriptionAr}</p>
</div>
<div className="project-info ">
<div className="col s6 project-info-icons left">
<i className="ion-ios-location-outline "></i>
<p>{product.location}</p>
<p>{product.locationAr}</p>
<br/>
<i className="ion-ios-home-outline"></i>
<p>{product.types}</p>
<br/>
<i className="ion-ios-photos-outline"></i>
<p>{product.area}</p>
<br/>
</div>
<div className="col s6 project-info-icons right">
<i className="ion-ios-pricetag-outline "></i>
<p>{product.installment} months installments</p>
<br/>
<i className="ion-ios-gear-outline"></i>
<p>{product.status}</p>
<br/>
<i className="ion-ios-cart-outline"></i>
<p>{product.deliveryDate}</p>
<br/>
</div>
<button className="more-details">MORE DETAILS</button>
</div>
</div>
</a>
)
})}
</Slider>
<div className="right-btn col s1">
<p>NEXT</p>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default ProjectsCarousel;

This might resolve issue with multiple element class toggling.try this out:
https://jsfiddle.net/menomanabdulla/todu7m6g/11/
class ToggoleApp extends React.Component {
constructor(props) {
super(props)
this.state = {
}
this.toggleClass=this.toggleClass.bind(this);
}
toggleClass(e){
let classes = 'my-class';
let els = document.getElementsByClassName('my-class active');
if(els){
while (els[0]) {
els[0].classList.remove('active')
}
}
e.target.className = classes.replace('my-class','my-class active');
}
render() {
return (
<div>
<h2>Toggle Example</h2>
<ul>
<li className="my-class active" onClick={(e) =>this.toggleClass(e)}>
One
</li>
<li className="my-class" onClick={(e) =>this.toggleClass(e)}>
Two
</li>
<li className="my-class" onClick={(e) =>this.toggleClass(e)}>
Three
</li>
</ul>
</div>
)
}
}
ReactDOM.render(<ToggoleApp />, document.querySelector("#app"))
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
.my-class{
color: #FF3355;
}
.my-class.active{
color: #33FF46;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>
<div id="app"></div>

From what I understand from after reading the question is you have to toggle between the elements on click by changing the class.
The solution I propose is change a single variable value onClick and use the variable to show and hide for example:
let isEnglish = true;
<h1 style={ display: isEnglish ? block : hidden }>{'Welcome'}</h1>
<h1 style={ display: isEnglish ? none : block }>{'Welcome in Arabic'}</h1>

Related

document.querySelector is not working in my react component

function Slider() {
const track=document.querySelector('.slide__track')//To access the div with class slide track
console.log(track);
return (
<div className="slider">
<i className="fas fa-chevron-left"></i>
<div className="head">
<h1 className="title">Based on your last search</h1>
<h6>View more</h6>
</div>
<div className="slider_container">
<ul className="slider__track">
<li className="slider__items">
<Card />
</li>
</ul>
</div>
<i className="fas fa-chevron-right"></i>
</div>
);
}
i cannot access the div with class slide__track.
What is the problem here?
Or how can i access that element?
Try and use this code in useEffect()
useEffect(() => {
const track = document.querySelector('.slide__track')
// have access to it
}, []);
I think it's because it is running before the DOM has been rendered. Move the track code into useEffect.
import {useEffect} from "react";
function Slider() {
useEffect(() => {
const track=document.querySelector('.slide__track')//To access the div with class slide track
console.log(track);
});
return (
<div className="slider">
<i className="fas fa-chevron-left"></i>
<div className="head">
<h1 className="title">Based on your last search</h1>
<h6>View more</h6>
</div>
<div className="slider_container">
<ul className="slider__track">
<li className="slider__items">
<Card />
</li>
</ul>
</div>
<i className="fas fa-chevron-right"></i>
</div>
);
}
You should be probably be using ref's to access dom elements inside react. see docs: https://reactjs.org/docs/refs-and-the-dom.html - reason being, if you have the below in a loop, or have multiple instances on the page, you'll need to be more careful with the selector approach.
import React, { useRef, useEffect } from 'react';
function Slider() {
const slideTrackRef = useRef(null);
useEffect(() => {
if (slideTrackRef && slideTrackRef.current) {
console.log(slideTrackRef.current);
}
}, [slideTrackRef]);
return (
<div className="slider">
<i className="fas fa-chevron-left" />
<div className="head">
<h1 className="title">Based on your last search</h1>
<h6>View more</h6>
</div>
<div className="slider_container">
<ul className="slider__track" ref={slideTrackRef}>
<li className="slider__items">
<p>tst</p>
</li>
</ul>
</div>
<i className="fas fa-chevron-right" />
</div>
);
}
export default Slider;

Calling data from the API for child component in Next.js

I am working on a header component. Here is the code:
import style from '../../styles/header.css';
import '../../styles/globals.css';
export default function Header({data}){
const [showMe, setShowMe] = useState(false);
function toggle(){
console.log("toggle")
setShowMe(!showMe);
}
return(
<>
<div className="header">
<div className="web-header">
<div className="first-header">
<div className="info-strip">
<ul>
<li>
Contact Us
</li>
<li>
7 Day Returns
</li>
<li>
Track Order
</li>
<li>
Return Order
</li>
<li>
Survey
</li>
</ul>
</div>
<div className="right-block d-flex">
<div className="login">
<span className="image"></span>
<span className="text">Log In
<div className="account-box">
</div>
</span>
</div>
<div className="cart">
<span className="cart-image">
</span>
<span className="text">Cart</span>
</div>
</div>
</div>
<div className="second-header">
<div className="header-logo">
<img src="https://www.mirraw.com/assets/logo-red.png" />
</div>
<div className="search">
<input placeholder="Search Something.." />
<button></button>
</div>
</div>
<div className="third-header">
<div className="container-fluid">
<ul className="menu">
{data.menus.map((post, index) => {
return (
<li className="menu-list">
{post.title}
<div className="megabox">
<ul className="wrapper">
{post.menu_columns.map((subItems, sIndex) => {
return <li>
<span className="menu-link">
{subItems.title}
</span>
<ul className="category">
{subItems.menu_items.map((x) => {
return <li>
{x.title}
</li>
})}
</ul>
</li>;
})}
</ul>
</div>
</li>)})}
</ul>
</div>
</div>
</div>
<div className="mobile-screen">
<div className="mobile-header">
<div className="mobile-menu">
<div className="menu-icon">
<div className="wrapper">
<input type="checkbox" id="navigation" />
<label for="navigation">
+
</label>
<div className="right-card">
<img src="https://www.mirraw.com/assets/logo-red.png" />
<p className="app-install">
<span>Download app</span>
</p>
<div className="cart">
<span className="cart-image"></span>
{/* <span className="text">Cart</span> */}
</div>
</div>
<nav>
<ul>
<li className="menu-heading">
<span>Menu</span>
<span>
<label for="navigation">X</label>
</span>
</li>
{data.menus.map((post, index) => {
return (
<li className="menu-list">
{post.title} <span onClick={toggle}>+</span>
<ul style={{display: showMe?"block":"none"}} className="category-one">
{post.menu_columns.map((subItems, sIndex) => {
return <li>
{subItems.title}
<span>+</span>
<ul className="category-two">
{subItems.menu_items.map((x) => {
return <li>
{x.title}
</li>
})}
</ul>
</li>;
})}
</ul>
</li>)})}
</ul>
</nav>
</div>
</div>
</div>
<div className="scroll-menu-list">
<ul className="mb-0">
{data.menus.map((post, index) => {
return (
<li className="menu-list">{post.title}</li>
)})}
</ul>
</div>
</div>
</div>
</div>
</>
)
}
export async function getServerSideProps() {
// Fetch data from external API
const res = await fetch(`https://api.mirraw.com/api/v1/menu`);
const data = await res.json();
// Pass data to the page via props
return { props: { data } }
}
Code is working fine if I render this page only, but when I import this component in other component, it threw error:
Server Error
TypeError: Cannot read property 'menus' of undefined
This error happened while generating the page. Any console logs will be displayed in the terminal window.
What could be the approach of getting value from the API for child component?
getServerSideProps can only be used within page components, which is why it works when you render this component as a page.
If you want to this to be a reusable component that can be called from other components and/or pages you'll need to pass the data you get at the page level (from getServerSideProps, for instance) down to it.
// pages/index.js
import Header from "../components/header"
export default function IndexPage({ data }) {
return (
<Header data={data} />
)
}
export async function getServerSideProps() {
const res = await fetch(`https://api.mirraw.com/api/v1/menu`);
const data = await res.json();
return { props: { data } }
}

how to get value from dropdown list in react?

class Navbar extends Component {
state = {};
getLink = (e) => {
const select = document.getElementById("drpdwn");
console.log(select.value);
};
render() {
return (
<>
<div className="container">
<nav className="navbar navbar-dark bg-primary">
<div
id="drpdwn"
onClick={() => this.getLink()}
className="dropdown"
>
<span className="dropbtn">Dropdown</span>
<div className="dropdown-content">
<a value="link1" href="#">
Link 1
</a>
<a value="link2" href="#">
Link 2
</a>
<a value="link3" href="#">
Link 3
</a>
</div>
</div>
</nav>
</div>
</>
);
}
}
export default Navbar;
All I want is whenever a user selects any link such as Link 1,2 or 3 I just want to get the value as simple as that. but all I'm getting is undefined. any suggestions??
You can change the code like this and use tags instead of and then tags.
import React, { Component } from "react";
class Navbar extends Component {
state = {};
getLink = (e) => {
const changeValue = e.target.value
console.log(changeValue )
};
render() {
return (
<>
<div className="container">
<nav className="navbar navbar-dark bg-primary">
<select
id="drpdwn"
onChange={(e) => this.getLink(e)}
className="dropdown"
>
<option value="link1" href="#">
Link 1
</option>
<option value="link2" href="#">
Link 2
</option>
<option value="link3" href="#">
Link 3
</option>
</select>
</nav>
</div>
</>
);
}
}
export default Navbar;
First, remove the anonymous function inside your onClick, like this :
onClick={this.getLink}
This will automatically pass the event into your function, so (e) will be defined. This is the equivalent of doing :
onClick={(e) => this.getLink(e)}
Once you've done that, you must recover the value inside the event in your function.
getLink = (e) => {
const value = e.target.value;
console.log(value);
};
I notice you want to create a navbar with a dropdown list
class Navbar extends Component {
render() {
return (
<>
<div className="container">
<nav className="navbar navbar-dark bg-primary">
<div
id="drpdwn"
onClickCapture={(e) => {
e.preventDefault();
// e.target which is the target you click within this div
console.log(e.target);
}}
className="dropdown"
>
<span className="dropbtn">Dropdown</span>
<div className="dropdown-content">
<a href="/">
Link 1
</a>
<a href="/">
Link 2
</a>
<a href="/">
Link 3
</a>
</div>
</div>
</nav>
</div>
</>
);
}
}
This is how you can do it.
import React, { Component } from "react";
class Navbar extends Component {
constructor(props) {
super(props);
this.ref = React.createRef();
}
getLink = ({ target }) => {
if (target.tagName.toLowerCase() === "a") {
console.log(target.getAttribute("value"));
}
};
render() {
return (
<>
<div className="container">
<nav className="navbar navbar-dark bg-primary">
<div id="drpdwn" onClick={this.getLink} className="dropdown">
<span className="dropbtn">Dropdown</span>
<div className="dropdown-content">
<a value="link1" href="#">
Link 1
</a>
<a value="link2" href="#">
Link 2
</a>
<a value="link3" href="#">
Link 3
</a>
</div>
</div>
</nav>
</div>
</>
);
}
}
export default Navbar;
You may try the demo in codesandbox
https://codesandbox.io/s/gettingthevalue-yeqoi

return value is not rendering when returned from inside the handleclick() function in react

import React from 'react';
import ReactDOM from 'react-dom';
import './home.css';
import {Link} from 'react-router';
class ChangeButton extends React.Component {
/* In this I want that when link one is click button corresponding to that
link should appear */
constructor(props) {
super(props);
this.state = {
arrayofval:[]
};
this.handleClick = this.handleClick.bind(this);
}
componentWillMount(){
this.setState({
arrayofval:[{label:'a',value:'ab'},
{label:'b',value:'bb'},
{label:'c',value:'cb'},
{label:'d',value:'db'},
{label:'e',value:'eb'}
]
})
}
handleClick(index){
if(index===0){
/* this button should appear if the first link is clicked*/
console.log("Come here if first link is clicked ")
return (<div>
<button className="button1">
Connect1
</button>
</div>);
}
else if(index===1)
{
console.log("Come here if second link is clicked ")
return <div>
<button className="button1">
Connect 2
</button>
</div>
}
else if(index===2){
console.log("Come here if 3rd link is clicked ")
return <div>
<button className="button1">
Connect 3
</button>
</div>
}
else if(index===3){
console.log("Come here if 4th link is clicked ")
return <div>
<div className="button1">
Connect 4
</div>
</div>
}
else{
console.log("Come here if 5th link is clicked ")
return <div>
<button className="button1">
Connect 5
</button>
</div>
}
}
render() {
return (
<div>
<div className="col-md-4 col-sm-4 col-xs-4">
<ul className="list-group">
<li className="list-group-item">
<a onClick={()=>this.handleClick(0)} href="#">{this.state.arrayofval[0].label}</a> </li>
<li className="list-group-item"><a onClick={()=>this.handleClick(1)} href="#">{this.state.arrayofval[1].label}</a> </li>
<li className="list-group-item"><a onClick={()=>this.handleClick(2)} href="#">{this.state.arrayofval[2].label}</a> </li>
<li className="list-group-item"><a onClick={()=>this.handleClick(3)} href="#">{this.state.arrayofval[3].label}</a> </li>
<li className="list-group-item"><a onClick={()=>this.handleClick(4)} href="#">{this.state.arrayofval[4].label}</a> </li>
</ul>
</div>
</div>
);
}
}
ReactDOM.render(
<ChangeButton />,
document.getElementById('app')
);
This is the code for displaying button according to the link clicked, so if link one is clicked the button with connect1 should be rendered.I am getting the link and when I am clicking on the link function is calling correct value also but the button is not coming.Suppose I click on the first link I got the console message for that but button has not appeared on the screen.
Return values from event listeners don't render anything. The only time something is rendered is in the render function. Event listeners happen in response to some event, not during the render process.
The way to handle this is would be to have your event listener set some state, and then render based on that:
handleClick(index) {
this.setState({
clicked: index
});
}
--
render() {
return (
<div>
<div className="col-md-4 col-sm-4 col-xs-4">
<ul className="list-group">
<li className="list-group-item">
<a onClick={()=>this.handleClick(0)} href="#">{this.state.arrayofval[0].label}</a>
</li>
<li className="list-group-item">
<a onClick={()=>this.handleClick(1)} href="#">{this.state.arrayofval[1].label}</a>
</li>
<li className="list-group-item">
<a onClick={()=>this.handleClick(2)} href="#">{this.state.arrayofval[2].label}</a>
</li>
<li className="list-group-item">
<a onClick={()=>this.handleClick(3)} href="#">{this.state.arrayofval[3].label}</a>
</li>
<li className="list-group-item">
<a onClick={()=>this.handleClick(4)} href="#">{this.state.arrayofval[4].label}</a>
</li>
</ul>
<div>
<button className="button1">
Connect {this.state.clicked + 1}
</button>
</div>
</div>
</div>
);
}
An even better way would be to use .map on your array:
render() {
return (
<div>
<div className="col-md-4 col-sm-4 col-xs-4">
<ul className="list-group">
{this.state.arrayofval.map((item, i) => (
<li className="list-group-item" key={i}>
<a onClick={() => this.handleClick(i)} href="#">{item.label}</a>
{this.state.clicked === i &&
<button className="button1">
Connect {this.state.clicked + 1}
</button>
}
</li>
))}
</ul>
</div>
</div>
);
}
I've never seen something like a click event returns a component.
You must think different way for best practises and use state I think.
import React from 'react';
import ReactDOM from 'react-dom';
import './home.css';
import {Link} from 'react-router';
class ChangeButton extends React.Component {
/* In this I want that when link one is click button corresponding to that
link should appear */
constructor(props) {
super(props);
this.state = {
arrayofval:[],
clicked: -1
};
this.handleClick = this.handleClick.bind(this);
}
componentWillMount(){
this.setState({
arrayofval:[{label:'a',value:'ab'},
{label:'b',value:'bb'},
{label:'c',value:'cb'},
{label:'d',value:'db'},
{label:'e',value:'eb'}
]
})
}
handleClick(index){
this.setState({clicked: index});
}
render() {
return (
<div>
<div className="col-md-4 col-sm-4 col-xs-4">
<ul className="list-group">
<li className="list-group-item">
<a onClick={()=>this.handleClick(0)} href="#">{this.state.arrayofval[0].label}</a>
{ this.state.clicked === 0 ? <button className="button1">Connect1</button> : null }
</li>
<li className="list-group-item">
<a onClick={()=>this.handleClick(1)} href="#">{this.state.arrayofval[1].label}</a>
{ this.state.clicked === 1 ? <button className="button1">Connect2</button> : null }
</li>
<li className="list-group-item">
<a onClick={()=>this.handleClick(2)} href="#">{this.state.arrayofval[2].label}</a>
{ this.state.clicked === 2 ? <button className="button1">Connect3</button> : null }
</li>
<li className="list-group-item">
<a onClick={()=>this.handleClick(3)} href="#">{this.state.arrayofval[3].label}</a>
{ this.state.clicked === 3 ? <button className="button1">Connect4</button> : null }
</li>
<li className="list-group-item">
<a onClick={()=>this.handleClick(4)} href="#">{this.state.arrayofval[4].label}</a>
{ this.state.clicked === 4 ? <button className="button1">Connect5</button> : null }
</li>
</ul>
</div>
</div>
);
}
}
ReactDOM.render(
<ChangeButton />,
document.getElementById('app')
);
You need a way to change state whenever the handleClick() method is called:
import React from 'react';
import ReactDOM from 'react-dom';
import './home.css';
import {Link} from 'react-router';
class ChangeButton extends React.Component {
/* In this I want that when link one is click button corresponding to that
link should appear */
constructor(props) {
super(props);
this.state = {
arrayofval:[]
index: 0 // this is where I track state change
};
this.handleClick = this.handleClick.bind(this);
}
componentWillMount(){
this.setState({
arrayofval:[{label:'a',value:'ab'},
{label:'b',value:'bb'},
{label:'c',value:'cb'},
{label:'d',value:'db'},
{label:'e',value:'eb'}
]
})
}
handleClick(index){
if(index===0){
/* this button should appear if the first link is clicked*/
console.log("Come here if first link is clicked ")
return (<div>
<button className="button1">
Connect1
</button>
</div>);
// set the index value in any of these conditions
}
else if(index===1)
{
console.log("Come here if second link is clicked ")
return <div>
<button className="button1">
Connect 2
</button>
</div>
}
else if(index===2){
console.log("Come here if 3rd link is clicked ")
return <div>
<button className="button1">
Connect 3
</button>
</div>
}
else if(index===3){
console.log("Come here if 4th link is clicked ")
return <div>
<div className="button1">
Connect 4
</div>
</div>
}
else{
console.log("Come here if 5th link is clicked ")
return <div>
<button className="button1">
Connect 5
</button>
</div>
}
}
render() {
return (
<div>
<div className="col-md-4 col-sm-4 col-xs-4">
<ul className="list-group">
<li className="list-group-item">
<a onClick={()=>this.handleClick(0)} href="#">{this.state.arrayofval[0].label}</a> </li>
<li className="list-group-item"><a onClick={()=>this.handleClick(1)} href="#">{this.state.arrayofval[1].label}</a> </li>
<li className="list-group-item"><a onClick={()=>this.handleClick(2)} href="#">{this.state.arrayofval[2].label}</a> </li>
<li className="list-group-item"><a onClick={()=>this.handleClick(3)} href="#">{this.state.arrayofval[3].label}</a> </li>
<li className="list-group-item"><a onClick={()=>this.handleClick(4)} href="#">{this.state.arrayofval[4].label}</a> </li>
</ul>
</div>
</div>
);
}
}
ReactDOM.render(
<ChangeButton />,
document.getElementById('app')
);
Calling setState() allows the component to re-render.

Converting JavaScript to work with React component

New to React and am trying to write my script in React but not sure how to do it.I've tried using states but that has just clouded me with more confusion. The below code is a sample of something I might commonly create.
Here's my script:
const hamburger = document.querySelector(".hamburger");
hamburger.addEventListener("click", function () {
hamburger.classList.toggle("is-active");
document.querySelector(".navigation").classList.toggle("slide-in");
document.querySelector("body").classList.toggle("menu-active");
document.querySelector(".shell-ui-main").classList.toggle("menu-overlay");
});
Here's a basic react component for a navbar:
import React from 'react';
export default class NavComponent extends React.Component {
render() {
return (
<div className="container">
<button className="hamburger hamburger--squeeze" type="button">
<span className="hamburger-box">
<span className="hamburger-inner"></span>
</span>
</button>
<a className="logo-link" href="/">
<img width="94" height="31" src="/img/logos/logo.png" srcSet="/img/logos/logo.png 1x, /img/logos/logo#2x.png 2x, /img/logos/logo#3x.png 3x"
alt="logo" className="logo" />
</a>
<nav className="navigation">
<ul className="nav">
<li className="single-item">
Home
</li>
<li className="single-item">
Item 2
</li>
<li className="single-item">
Item 3
</li>
<li className="single-item">
Item 4
</li>
</ul>
</nav>
</div>
);
}
}
Here's the solution in case anyone is interested. Additionally I pass the props down to the component and control from there instead of the individual const.
import React from 'react';
const HamburgerToggle = (props) => (
<button className={"hamburger hamburger--squeeze" + (props.active ? " is-active" : "")} onClick={props.clickHandler} type="button">
<span className="hamburger-box">
<span className="hamburger-inner"></span>
</span>
</button>
);
const Logo = () => (
<a className="logo-link" href="/">
<img width="94" height="31" src="/img/logos/logo.png" srcSet="/img/logos/logo.png 1x, /img/logos/logo#2x.png 2x, /img/logos/logo#3x.png 3x" alt="Logo" className="logo" />
</a>
);
const Navigation = (props) => (
<nav className={"navigation" + (props.active ? " slide-in" : "")}>
<ul className="nav">
<li className="single-item">
Home
</li>
<li className="single-item">
intem 2
</li>
<li className="single-item">
item 3
</li>
<li className="single-item">
item 4
</li>
</ul>
</nav>
);
export default class NavComponent extends React.Component {
state = {active: false};
handleClick(e){
this.setState({active: !this.state.active});
console.log(this.state.active);
}
render() {
return (
<div className="container">
<HamburgerToggle active={this.state.active} clickHandler={this.handleClick.bind(this)} />
<Logo />
<Navigation active={this.state.active} clickHandler={this.handleClick.bind(this)} />
</div>
);
}
}

Categories

Resources