how to add items to var #<Object> in React - reactjs

I have the next var in the render method, but I want to add more items in the div id='test'
export default class Home extends React.Component {
render() {
let view = <div id='test' className='container is-fluid'>
<div class="tile is-parent">
<article class="tile is-child box">
<p class="title">Hello World</p>
<p class="subtitle">What is up?</p>
</article>
</div>
</div>
return (
{var}
)
}
and I want something like
view.appendChild(
<div class="tile is-parent">
<article class="tile is-child box">
<p class="title">Hello World</p>
<p class="subtitle">What is up?</p>
</article>
</div>
)

Related

Unable to use div components with bootstrap classes inside map function in react

I have passed the data via props, the console logs show me the data being passed. here is the code below
import React, { Component } from 'react';
import "../../../node_modules/bootstrap/dist/css/bootstrap.min.css";
import "./TestimonialCard.css";
const Cards = ({cardData}) =>{
console.log(cardData);
return(
<>
<div className="container">
<div className="row">
<div className="col-md-8 col-center m-auto">
<h2>Testimonials</h2>
<div id="myCarousel" className="carousel slide" data-ride="carousel" >
<div className="carousel-inner">
{cardData.map((slide , index )=>{
{console.log(slide)}
<div className="item carousel-item active" key={index} >
<div className="img-box">
<img src={slide.image} alt={slide.alt}/>
</div>
<p className="testimonial">
{slide.testimonial}
</p>
<p className="overview">
<b> {slide.name} </b> ,<span>{slide.designation}</span>
</p>
</div>
})}
</div>
<a className="carousel-control left carousel-control-prev" href="myCarousel" data-slide="prev">
<i className="fa fa-angle-left"></i>
</a>
<a className="carousel-control right carousel-control-next" href="myCarousel" data-slide="next">
<i className="fa fa-angle-right"></i>
</a>
</div>
</div>
</div>
</div>
</>
)
}
export default Cards
Here, I'm not getting an expected UI under my div with carousel-inner class.
You can use it like this:
import React, { Component } from 'react';
import "../../../node_modules/bootstrap/dist/css/bootstrap.min.css";
import "./TestimonialCard.css";
const Cards = ({cardData}) =>{
console.log(cardData);
const cardData = (cardData) => {
cardData.map((slide, index) => {
return (
<div className="item carousel-item active" key={index}>
<div className="img-box">
<img src={slide.image} alt={slide.alt}/>
</div>
<p className="testimonial">
{slide.testimonial}
</p>
<p className="overview">
<b> {slide.name} </b> ,<span>{slide.designation}</span>
</p>
</div>
)
})
}
return(
<>
<div className="container">
<div className="row">
<div className="col-md-8 col-center m-auto">
<h2>Testimonials</h2>
<div id="myCarousel" className="carousel slide" data-ride="carousel" >
<div className="carousel-inner">
{cardData()}
</div>
<a className="carousel-control left carousel-control-prev" href="myCarousel" data-slide="prev">
<i className="fa fa-angle-left"></i>
</a>
<a className="carousel-control right carousel-control-next" href="myCarousel" data-slide="next">
<i className="fa fa-angle-right"></i>
</a>
</div>
</div>
</div>
</div>
</>
)
}
export default Cards
The reason UI was not rendering is because you are using {} instead of () in map inside JSX.
If you want to use map inside render() or the JSX you need to use () instead of {} like this:
{cardData.map((slide , index )=> (
{console.log(slide)}
<div className="item carousel-item active" key={index} >
<div className="img-box">
<img src={slide.image} alt={slide.alt}/>
</div>
<p className="testimonial">
{slide.testimonial}
</p>
<p className="overview">
<b> {slide.name} </b> ,<span>{slide.designation}</span>
</p>
</div>
))}

How do I toggle sidebar on React

I have a toggle example that I have done with Jquery before. Now I want to do it with react, but I don't know how.
I'm putting my Jquery code and React design code below.
React Design Code
Sidebar.js
`
import React from 'react';
import profileImage from '../../../assets/img/profil.jpg';
import iconImage from '../../../assets/img/icon.jpg';
import businessManImage from '../../../assets/img/business-man-white.svg';
import preferencessImage from '../../../assets/img/cogs-white.svg';
import logoutImage from '../../../assets/img/logout.svg';
import toggleImage from '../../../assets/img/toggle-icon.png';
import profileWhite from '../../../assets/img/profile-white.svg';
import classes from '../Sidebar/Sidebar.module.css';
const Sidebar = (props) => {
let url = ""
return (
<div>
<div className={classes['side-bar']}>
<div className={classes['side-bar-top']}>
<div className={classes['side-bar-icon']}>
<img src={iconImage} alt="profileresmi" />
</div>
</div>
<div className={classes['side-bar-row']} style={{height: '100px'}} >
<div className={classes['side-bar-icons']} style={{width: '100px'}} >
<div className={classes['side-bar-profile-image']}>
<img src={profileImage} alt="profileresmi" />
</div>
</div>
<div className={classes['side-bar-profile-content']}>
<h3><b>Mert EKİNCİ</b></h3>
<h4>mert#akturk.de</h4>
</div>
</div>
<div className={classes['side-bar-row']}>
<div className={classes['side-bar-icons']}>
<a href={url} className={classes['side-bar-elements-icons']}>
<img src={businessManImage} alt="profileresmi" />
</a>
</div>
<div className={classes['side-bar-text']}>
<a href={url}>Processes</a>
</div>
</div>
<div style={{ clear: 'both' }} ></div>
<div className={classes['side-bar-row']}>
<div className={classes['side-bar-icons']}>
<a href={url} className={classes['side-bar-elements-icons']}>
<img src={preferencessImage} alt="profileresmi" />
</a>
</div>
<div className={classes['side-bar-text']}>
<a href={url}>Preferences</a>
</div>
</div>
<div className={classes['side-bar-row']}>
<div className={classes['side-bar-icons']}>
<a href={url} className={classes['side-bar-elements-icons']}>
<img src={profileWhite} alt="profileresmi" />
</a>
</div>
<div className={classes['side-bar-text']}>
<a href={url}>User</a>
</div>
</div>
<div className={classes['side-bar-row']}>
<div className={classes['side-bar-icons']}>
<a href={url} className={classes['side-bar-elements-icons']}>
<img src={logoutImage} alt="profileresmi" />
</a>
</div>
<div className={classes['side-bar-text']}>
<a href={url}>Logout</a>
</div>
</div>
</div>
<div className={classes['side-toggle']}>
<span className={classes['side-bar-toggle']} >
<img src={toggleImage} alt="profileresmi" />
</span>
</div>
</div>
);
}
export default Sidebar;
`
Here I made the toggle by hiding and showing my divs.
Jquery Sidebar Toggle Code
Script.js
`
var isToggled = true;
var toggleDelay = 50;
var onclickSideToggle = function () {
isToggled = !isToggled;
toggleSidebar(isToggled);
};
$('#side-bar-toggle').on('click', onclickSideToggle);
var toggleSidebar = function (toggle) {
if (toggle) {
$('.side-bar-text').show(toggleDelay);
$('.side-bar-profile-content').show(toggleDelay);
} else {
$(".side-bar-text").hide(toggleDelay);
$('.side-bar-profile-content').hide(toggleDelay);
}
};
`
Can you give me some information on how to do it with React?
If you want just hide/show without any animation you can use the following approach.
More info about usage of useState hook you can find here: https://reactjs.org/docs/hooks-reference.html#usestate
import React, { useState } from 'react';
import profileImage from '../../../assets/img/profil.jpg';
import iconImage from '../../../assets/img/icon.jpg';
import businessManImage from '../../../assets/img/business-man-white.svg';
import preferencessImage from '../../../assets/img/cogs-white.svg';
import logoutImage from '../../../assets/img/logout.svg';
import toggleImage from '../../../assets/img/toggle-icon.png';
import profileWhite from '../../../assets/img/profile-white.svg';
import classes from '../Sidebar/Sidebar.module.css';
const Sidebar = props => {
const [isContentToggled, setIsContentToggled] = useState(true);
let url = ""
return (
<div>
<div className={classes['side-bar']}>
<div className={classes['side-bar-top']}>
<div className={classes['side-bar-icon']}>
<img src={iconImage} alt="profileresmi" />
</div>
</div>
<div className={classes['side-bar-row']} style={{height: '100px'}} >
<div className={classes['side-bar-icons']} style={{width: '100px'}} >
<div className={classes['side-bar-profile-image']}>
<img src={profileImage} alt="profileresmi" />
</div>
</div>
{isContentToggled && (
<div className={classes['side-bar-profile-content']}>
<h3><b>Mert EKİNCİ</b></h3>
<h4>mert#akturk.de</h4>
</div>
)};
</div>
<div className={classes['side-bar-row']}>
<div className={classes['side-bar-icons']}>
<a href={url} className={classes['side-bar-elements-icons']}>
<img src={businessManImage} alt="profileresmi" />
</a>
</div>
{isContentToggled && (
<div className={classes['side-bar-text']}>
<a href={url}>Processes</a>
</div>
)}
</div>
<div style={{ clear: 'both' }} ></div>
<div className={classes['side-bar-row']}>
<div className={classes['side-bar-icons']}>
<a href={url} className={classes['side-bar-elements-icons']}>
<img src={preferencessImage} alt="profileresmi" />
</a>
</div>
{isContentToggled && (
<div className={classes['side-bar-text']}>
<a href={url}>Preferences</a>
</div>
)}
</div>
<div className={classes['side-bar-row']}>
<div className={classes['side-bar-icons']}>
<a href={url} className={classes['side-bar-elements-icons']}>
<img src={profileWhite} alt="profileresmi" />
</a>
</div>
{isContentToggled && (
<div className={classes['side-bar-text']}>
<a href={url}>User</a>
</div>
)}
</div>
<div className={classes['side-bar-row']}>
<div className={classes['side-bar-icons']}>
<a href={url} className={classes['side-bar-elements-icons']}>
<img src={logoutImage} alt="profileresmi" />
</a>
</div>
{isContentToggled && (
<div className={classes['side-bar-text']}>
<a href={url}>Logout</a>
</div>
)}
</div>
</div>
<div className={classes['side-toggle']}>
<span onClick={() => setIsContentToggled(prevIsContentToggled => !prevIsContentToggled)} className={classes['side-bar-toggle']}>
<img src={toggleImage} alt="profileresmi" />
</span>
</div>
</div>
);
}
export default Sidebar;
If you want to toggle with the animation code will be almost the same.
You will need just to create some additional className like .hidden with styles for hidden elements and replace
{isContentToggled && (
<div className={classes['side-bar-profile-content']}>
<h3><b>Mert EKİNCİ</b></h3>
<h4>mert#akturk.de</h4>
</div>
)};
with adding/removing this className depending on the isContentToggled value.

React - How to pass props down for the .map function when using functional components

How can I pass the props from the ProductFeatures to the renderFeatures function ?
Below is a sample code:
const renderFeatures = (feature) => {
return (
<div key={feature.productFeatureTypeId} className="panel panel-default">
<div className="panel-heading">
<div className="row row-no-border row-h-10">
<div className="col-xs-10">
<a
className="accordion-toggle"
data-toggle="collapse"
href={"#" + feature.productFeatureTypeId}
>
<h4 className="panel-title">{feature.productFeatureTypeId}</h4>
</a>
</div>
<div className="col-xs-2 text-right font-size-16">
<span className="glyphicon glyphicon-circle-arrow-down"></span>
</div>
</div>
</div>
<div
id={feature.productFeatureTypeId}
className="panel-collapse collapse in"
>
<div className="panel-body">
{feature.productFeaturesDescription.map(renderFeatureObjItem)}
</div>
</div>
</div>
);
};
const ProductFeatures = (props) => {
let mappedProductFeaturesMembers = getMappedProductFeaturesMembers(
props.product.productFeatureMembers
);
return (
<div className="panel-group" id="accordion">
{mappedProductFeaturesMembers.map(renderFeatures)}
</div>
);
};
Note that all this code is inside one file named ProductFeatures.js and I am using functional components.
You can just pass it in the rednerFeatures like this:
const renderFeatures = (feature, props) => { // Accept both feature and props
return (
<div key={feature.productFeatureTypeId} className="panel panel-default">
<div className="panel-heading">
<div className="row row-no-border row-h-10">
<div className="col-xs-10">
<a
className="accordion-toggle"
data-toggle="collapse"
href={"#" + feature.productFeatureTypeId}
>
<h4 className="panel-title">{feature.productFeatureTypeId}</h4>
</a>
</div>
<div className="col-xs-2 text-right font-size-16">
<span className="glyphicon glyphicon-circle-arrow-down"></span>
</div>
</div>
</div>
<div
id={feature.productFeatureTypeId}
className="panel-collapse collapse in"
>
<div className="panel-body">
{feature.productFeaturesDescription.map(renderFeatureObjItem)}
</div>
</div>
</div>
);
};
const ProductFeatures = (props) => {
let mappedProductFeaturesMembers = getMappedProductFeaturesMembers(
props.product.productFeatureMembers
);
return (
<div className="panel-group" id="accordion">
{mappedProductFeaturesMembers.map(feature => renderFeatures(feature, props))} // Pass props here too
</div>
);
};

Make wrapper component in React

I am trying to make a component such that it holds another HTML element along with the React custom components. I created the component but it didn't work as I want. Currently, it didn't get rendered.
whole component structure
<AddingDetail>
<div className="row">
<DetailHeader link="/dashboard/setting" linkText="Back" heading="Add Role" />
<DetailBody>
<h1>Hello</h1>
</DetailBody>
<DetailFooter buttonText="Add" />
</div>
</AddingDetail>
AddingDetail component
render()
{
return(
<div className="col-md-12 bg-white border-radius-10">
</div>
)
}
DetailBody
render()
{
return(
<div className="col-md-12">
</div>
)
}
DetailHeader
return(
<div className="col-md-12 mgb-30" style={border} >
<div className="row" style={{marginBottom:'10px'}}>
<div className="col-md-6 flex vertical-center">
<h3 className="sub-heading roboto mgb-0">{this.props.heading}</h3>
</div>
<div className="col-md-6 align-right flex vertical-center flex-end">
<Link to={this.props.link}>
<button type="button" className="golden-button">{this.props.linkText}}</button>
</Link>
</div>
</div>
</div>
)
DetailFooter
return(
<div className="col-md-12 align-center mgb-20 mgt-20">
<button type="button" className="golden-button">{this.props.buttonText}</button>
</div>
)
You can use props.children to show the content in AddingDetail :
render() {
return(
<div className="col-md-12 bg-white border-radius-10">
{ this.props.children } //<---- HERE
</div>
)
}
And the same change you can apply to DetailBody.
render() {
return(
<div className="col-md-12">
{ this.props.children }
</div>
)
}

In react js this.state getting state of null in function

I want to change backgroundColor on hover but getting error when onMouseOver function get call it says "Uncaught TypeError: Cannot read property 'setState' of null" in console. Please let me know what is wrong with this code thanks.
import React from 'react'
import { Link } from 'react-router'
import { prefixLink } from 'gatsby-helpers'
import Helmet from 'react-helmet'
import { config } from 'config'
export default class Index extends React.Component {
constructor(props) {
super(props);
this.state = {
header: "harry header",
content: "content for harry",
activeClass : 'normal',
hovered :false
}
}
componentDidMount(){
var cssClass = 'normal';
window.addEventListener('scroll', (event) => {
if(event.srcElement.body.scrollTop == 0){
cssClass = 'normal';
}else{
cssClass = 'fixed';
}
this.setState({
activeClass: cssClass,
})
});
}
style() {
if (this.state.hovered) {
return { backgroundColor: "red" }
} else {
return { backgroundColor: "grey" }
}
}
onMouseOver (){
this.setState({ hovered:true });
}
onMouseOut (){
this.setState({ hovered:false });
}
render() {
return (
<div>
<header className={`header ${this.state.activeClass}`} >
<div className="top-bar">
<span>678-827-2782 </span>
<span> hellohello#knotel.com</span>
<button>Login</button>
</div>
</header>
<div className="banner-main-outer">
<div className="banner-main">
</div>
<div className="abs-height-caption">
<div className="caption-banner">
<div className="logo-main"><img src={require('../img/knotel.svg')}/></div>
<h2>Commit to your business, not a lease</h2>
<span>Headquarters as a Service</span>
<button>Book a tour</button>
</div>
<ul className="kno-ul">
<li><a> LOCATIONS</a></li>
<li><a> SPACES</a></li>
<li><a> Services</a></li>
<li><a> Events</a></li>
<li className="kno-hiring"><a> We're hiring</a></li>
</ul>
</div>
<div className="banner-btm-link">
<a>Tenant Reps</a>
<a>I have space</a>
</div>
</div>
<div className="Spaces-Offer">
<div className="header-bar">Our Locations</div>
<div className="map-outer">
<img src={require('../img/map.jpg')} />
</div>
</div>
<div className="our-offer">
<div className="header-bar">Spaces We Offer</div>
<div onMouseOver={this.onMouseOver}
onMouseOut={this.onMouseOut}
style={this.style()} className="offer-cards">
<ul>
<li className="blue-block">
<h1>Flexible Workspace For Growing Teams</h1>
<p>We provide the resources so growing teams can focus their business. Many of our companies have graduated from coworking spaces.</p>
<div className="offer-res-img" />
</li>
<li className="brown-block">
<h1>Branded Floors for Established Companies</h1>
<p>When you need your own floor we provide dedicated, branded space for your company with a backbone of Knotel management.</p>
<div className="offer-res-img" />
</li>
<li className="purple-block">
<h1>Flagship Buildings for World Leaders</h1>
<p>When you are ready to take over the world, Knotel will take over a building for you. Turnkey commercial real estate at any size.</p>
<div className="offer-res-img" />
</li>
</ul>
</div>
</div>
<div className="our-services">
<div className="header-bar">Services We Provide</div>
<div className="sources-cards">
<ul>
<li className="active">
<h1>Sourcing and Buildout</h1>
<p>Knotel bundles property market insight with interior design expertise and buildout management, which ensures the client’s space vision is met on time, on budget, and without headaches.</p>
<div className="sources-res-img" />
</li>
<li>
<h1>Seamless Operations</h1>
<p>Knotel provides comprehensive office services powered by domain experts and best of breed technology. Enjoy the highest ratio of conference rooms per person in the industry, and exclusive deals at a high quality set of partners</p>
<div className="sources-res-img" />
</li>
<li>
<h1>Flexible Terms</h1>
<p>Knotel has a simple pricing structure with flexible terms. We offer various month to month and fixed term agreements tailored to your needs.</p>
<div className="sources-res-img" />
</li>
<li>
<h1>Events and Community</h1>
<p>Knotels are vibrant spaces, with engaged communities and a strong roster of events. Enjoy office hours and informal access to like-minded industry professionals.</p>
<div className="sources-res-img" />
</li>
</ul>
<div className="source-img-change" />
</div>
</div>
<div className="our-events">
<div className="header-bar">Events we're hosting</div>
<div className="form-contact">
<div className="main-outer-inp">
<h1>Stay in the know about Knotel events and news</h1>
<div className="input-blocks">
<input placeholder="First Name (required)" type="text" />
</div>
<div className="input-blocks">
<input placeholder="Last Name (required)" type="text" />
</div>
<div className="input-blocks">
<input placeholder="Email (required)" type="text" />
</div>
</div>
<div className="sub-btn">
<button>SUBSCRIBE</button>
</div>
</div>
</div>
<div className="structure-events">
<div className="structure-container">
<div className="events-details">
<div className="events-knotels">COMING EVENTS</div>
<ul>
<li>
<div className="img-block"><img src={require('../img/manhattan-logo.jpg')} /></div>
<div className="eventdetail">
<div className="dates-on">
<span>07</span>
<p>Jun</p>
</div>
<div className="gtm-para">
<span>Entrepreneurship Council</span>
<p>8:30 am to 10:00 am at Knotel </p>
</div>
</div>
</li>
<li>
<div className="img-block"><img src={require('../img/Parrot Memento Knotel.png')} /></div>
<div className="eventdetail">
<div className="dates-on">
<span>14</span>
<p>Feb</p>
</div>
<div className="gtm-para">
<span>Knotel Private Founders Series</span>
<p>5:00 pm to 7:00 pm at Knotel Union Sq 1</p>
</div>
</div>
</li>
</ul>
</div>
<div className="events-details">
<div className="events-knotels">PAST EVENTS</div>
<ul>
<li>
<div className="img-block"><img src={require('../img/DLD2.jpg')} /></div>
<div className="eventdetail">
<div className="dates-on">
<span>12</span>
<p>May</p>
</div>
<div className="gtm-para">
<span>Future Of Cities - DLD NYC</span>
<p>8:00 am to 2:00 pm at Knotel Bryant </p>
</div>
</div>
</li>
<li>
<div className="img-block"><img src={require('../img/health.jpg')} /></div>
<div className="eventdetail">
<div className="dates-on">
<span>25</span>
<p>Apr</p>
</div>
<div className="gtm-para">
<span>Health Tech Founders' Stories</span>
<p>6:30 pm to 8:30 pm at Knotel Bryant</p>
</div>
</div>
</li>
<li>
<div className="img-block"><img src={require('../img/Space.jpg')} /></div>
<div className="eventdetail">
<div className="dates-on">
<span>20</span>
<p>Apr</p>
</div>
<div className="gtm-para">
<span>When Do We Go To Space?</span>
<p>6:30 pm to 8:30 pm at Knotel Bryant</p>
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
<footer>
<div className="footer">
<div className="img-footer">
<img src={require('../img/knotel.svg')} />
</div>
<ul>
<li><a>Careers</a></li>
<li><a>Terms</a></li>
<li><a>Tenant Reps</a></li>
<li><a>I have space</a></li>
</ul>
<div className="Copyright-res">Copyright © 2017 KNOTEL. All rights reserved.</div>
</div>
</footer>
</div>
)
}
}
From the docs:
You have to be careful about the meaning of this in JSX callbacks. In JavaScript, class methods are not bound by default. If you forget to bind this.handleClick and pass it to onClick, this will be undefined when the function is actually called.
This is not React-specific behavior; it is a part of how functions work in JavaScript.
So you need to bind this to your methods to in order to make it work.
This is how your constructor should look:
constructor(props) {
super(props);
this.state = {
header: "harry header",
content: "content for harry",
activeClass: "normal",
hovered: false
}
this.onMouseOver = this.onMouseOver.bind(this)
this.onMouseOut = this.onMouseOut.bind(this)
}
You need to bind you class methods to this instance. One way to do that is in the constructor -
constructor(props) {
super(props);
this.onMouseOver = this.onMouseOver.bind(this)
this.onMouseOut = this.onMouseOut.bind(this)
this.state = {
header: "harry header",
content: "content for harry",
activeClass : 'normal',
hovered :false
}
}
Whenever you get an error which you can trace back to cannot read property x of null where null was supposed to be this, you know that the binding for this is not correct at the time the method/function was called.
The other answers are correct, but you can also add the events to the higher order <div>
so you can modify your component to be like
return (
<div onMouseOut={this.onMouseOut} onMouseOver={this.onMouseOver}>
...
</div>
);

Resources