Can't binding reference this in React - reactjs

Im trying to create a ReactList that contains the activities on state, but i can't manage to reference the variable state from inside renderItemOtherActi when called as
itemRenderer={this.renderItemOtherActi}
I tryed using
itemRenderer={::this.renderItemOtherActi}
or
itemRenderer={this.renderItemOtherActi.bind(this)}
but nothing worked, I'm sure it's a really dumb mistake, sorry in advance im new in JSX. Thanks a lot!
import React from 'react';
import ReactList from 'react-list';
import './css/bootstrap.min.css';
import './css/small-business.css';
import Navbar from './Navbar';
import Footer from './Footer';
class Activity_Page extends React.Component {
state = {
my_activities: [
{
name:"Yoga"
},
{
name:"Crossfit"
}],
other_activities: [
{
name:"Zamba"
},
{
name:"Spinnig"
}]
};
return_state(){
return this.state;
}
renderItemMyActi(index, key) {
return <div key={key}>Yoga</div>;
}
renderItemOtherActi(index, key) {
return <div key={key}>{this.state.my_activities[index].name}</div>;
}
render() {
return (
<div>
<Navbar />
<div className="Activity_Page container">
<div className="row">
<div className="col-lg-10">
<h3>Actividades a las que estoy inscripto</h3>
<div style={{overflow: 'auto', maxHeight: 400}}>
<ReactList
itemRenderer={this.renderItemMyActi}
length={this.state.my_activities.length}
type='uniform'
/>
</div>
<h3>Actividades a las que no estoy inscripto</h3>
<div style={{overflow: 'auto', maxHeight: 400}}>
<ReactList
itemRenderer={this.renderItemOtherActi}
length={this.state.other_activities.length}
type='uniform'
/>
</div>
</div>
</div>
<footer className="Footer">
<div className="row">
<div className="col-lg-12">
<Footer />
</div>
</div>
</footer>
</div>
</div>
);
}
}
export default Activity_Page;

you either
bind it in the constructor:
constructor(props){
super(props);
this.renderItemOtherActi=this.renderItemOtherActi.bind(this);
}
or use arrow function
renderItemOtherActi = (index, key) => {
// ...
}

Related

UPDATE: Problems with GPT ads implementation (React app) partially fixed

I am trying to return a test ad on my React app news feed but NPM seems to be lacking documentation. The only thing out there that I can find is from eBayClassifiedsGroup/react-advertising. Here's the code I have for Step1 (see lines 46-54):
import React, { Component } from 'react';
import './App.css';
import News from './News/News';
import SideFeed from './News/SideFeed';
import {
AdvertisingProvider,
AdvertisingSlot,
} from 'react-advertising';
import config from './News/config'
class App extends Component {
constructor(props) {
super(props);
this.state = {
news1: {
type: 'top-headlines',
query: 'sources=bbc-news'
},
news2: {
type: 'everything',
query: 'domains=techcrunch.com&language=en'
},
news3: {
type: 'everything',
query: 'domains=comicbookmovie.com&language=en'
}
};
}
render() {
return (
<div className="container-fluid">
<div className="navbar-fixed">
<nav>
<div className="nav-wrapper indigo lighten-4">
RF News Feed as of 6 DEC 2021
</div>
</nav>
</div>
<div className="row">
<div className="col s8">
<News news={this.state.news1} />
<News news={this.state.news2} />
<div id="banner-ad"
style= { {
width: 300,
height: 250
}}>
<AdvertisingProvider config={config} />
<AdvertisingSlot config={config} />
</div>
</div>
<div className="col s4">
<SideFeed news={this.state.news3}/>
</div>
</div>
</div>
);
}
}
export default App;
Step 2: The only ad dependency is in config.js which is below:
import React from 'react';
const config = {
slots: [
{
id: "banner-ad",
path: "/6355419/Travel/Europe/France/Paris",
sizes: [[300, 250]]
}
]
};
export default config;
Can anyone take a gander or refer me to a resource re: GPT ads implementation for React?

Why Inline Styling style={{maxHeight:'443 px', maxWidth: '443 px'}} is not working in component

Tysm for help in advance!
I am doing famous react Course of Coursera!
IN App.js Menu is rendered as Component. MenuComponent.js is as follows:
import React,{Component} from 'react';
import DishDetail from './DishDetail';
import { Card, CardImg, CardImgOverlay} from 'reactstrap';
class Menu extends Component {
constructor(props) {
super(props);
this.state = {
selectedDish: null
}
}
onDishSelect(dish) {
this.setState({ selectedDish: dish});
}
renderDish() {
if (this.state.selectedDish)
return <DishDetail dish={this.state.selectedDish} />;
else
return(
<div></div>
);
}
render() {
const menu = this.props.dishes.map((dish) => {
return (
<Card
key={dish.id}
className="col-12 col-md-5 m-1"
onClick={() => this.onDishSelect(dish)}
>
<CardImg width="100%" className="card-img-top" src={dish.image} alt={dish.name} />
<CardImgOverlay className="card-image-overlay">
<h5>{dish.name}</h5>
</CardImgOverlay>
</Card>
);
});
return (
<div className="container">
<div className="row">
{menu}
</div>
<div className="row">
<div classNmae="col-12 col-md-5 m-1">
{this.renderDish(this.state.selectedDish)}
</div>
</div>
</div>
);
}
}
export default Menu;
DishDetail.js is as follows:
import React, { Component } from 'react';
import { Card, CardImg, CardText, CardBody,CardTitle} from 'reactstrap';
class DishDetail extends Component {
render () {
return (<div className="row">
<div classname="col-6 col-md-4" >
<Card>
<CardImg style={{maxWidth:'443 px', maxHeight:'443 px'}} top src={this.props.dish.image} alt={this.props.dish.name} />
<CardBody>
<CardTitle>{this.props.dish.name}</CardTitle>
<CardText className="text-center">{this.props.dish.description}</CardText>
</CardBody>
</Card>
</div>
<div className="col-6 col-md-4">
<h3>Comments</h3>
{
this.props.dish.comments.map( (comment) => {
return (
<div id={comment.id}>
<p>{comment.comment}</p>
<p>--{comment.author} , {comment.date}</p>
</div>
)
})
}
</div>
</div>
);
}
}
export default DishDetail;
I want render Dish Detail and it's comments in form col-6 col-6 means side by side. But Instead of that, I am getting output like:-
Desired Output is like:
Tysm for solving in advance!
Try to use it this way:
import React, { Component } from 'react';
import { Card, CardImg, CardText, CardBody,CardTitle} from 'reactstrap';
class DishDetail extends Component {
render () {
const myStyle = {
maxWidth:'443px',
maxHeight:'443px'
}
return (<div className="row">
<div classname="col-6 col-md-4" >
<Card>
<CardImg style={myStyle} top src={this.props.dish.image} alt={this.props.dish.name} />
<CardBody>
<CardTitle>{this.props.dish.name}</CardTitle>
<CardText className="text-center">{this.props.dish.description}</CardText>
</CardBody>
</Card>
</div>
<div className="col-6 col-md-4">
<h3>Comments</h3>
{
this.props.dish.comments.map( (comment) => {
return (
<div id={comment.id}>
<p>{comment.comment}</p>
<p>--{comment.author} , {comment.date}</p>
</div>
)
})
}
</div>
</div>
);
}
}
export default DishDetail;
https://www.w3schools.com/react/showreact.asp?filename=demo2_react_css_inline_object
It's a 443px unit, there is no space between 443 and px. Otherwise, the CSS will not be applied to your selected element.
<Card>
<CardImg
style={{ maxWidth: "443px", maxHeight: "443px" }}
top
src={this.props.dish.image}
alt={this.props.dish.name}
/>
<CardBody>
<CardTitle>{this.props.dish.name}</CardTitle>
<CardText className="text-center">{this.props.dish.description}</CardText>
</CardBody>
</Card>
One more example where 10 px (with space) unit will not work.
import React from 'react';
export default class App extends React.Component {
render() {
const mystyle = {
color: "white",
backgroundColor: "DodgerBlue",
padding: "10 px", // check here not applied
fontFamily: "Arial"
};
return (
<div>
<h1 style={mystyle}>Hello Style!</h1>
<p>Add a little style!</p>
</div>
);
}
}
Demo on Sandbox

How to place a rendered element in a div in ReactJs

I'm new in ReactJs and I only know a few things as of now. I'm trying to create this Google map with directions which is successful
MapRender.js
import React from 'react';
import { render } from 'react-dom';
import Map from './mapProps';
//import './style.css';
const googleMapsApiKey = "API_KEY";
export default function FinalMap() {
const FinalMap = props => {
const {places} = props;
const {
loadingElement,
containerElement,
mapElement,
defaultCenter,
defaultZoom
} = props;
return (
<Map
googleMapURL={
'https://maps.googleapis.com/maps/api/js?key=' +
googleMapsApiKey +
'&libraries=geometry,drawing,places'
}
markers={places}
loadingElement={loadingElement || <div style={{height: `100%`}}/>}
containerElement={containerElement || <div style={{height: "80vh"}}/>}
mapElement={mapElement || <div style={{height: `100%`}}/>}
defaultCenter={defaultCenter || {lat: 25.798939, lng: -80.291409}}
defaultZoom={defaultZoom || 13}
/>
);
};
const places = [
{latitude:14.7539407,longitude:121.0338431},
{latitude: 14.625981794368357,longitude: 121.06170033978614},
]
render(<FinalMap defaultZoom={12} places={places} />, document.getElementById('root'));
}
And this is my App.js
import React from 'react';
import picture1 from '../../src/picture1.jpg';
import RechartBar from '../postlist/Rechart-Bar';
import RechartLine from '../postlist/Rechart-Line';
import driverstat from '../driverprofiles/driverstat';
import AppMap from './Maps/map';
import MapRender from './Maps/MapRender';
function Home() {
return (
<div className="Bodydiv">
<div className="homediv">
<div className="userdiv">
<div className="userdiv-profile">
<div className="userdiv-profile-photo">
<img src={picture1} className="photo" alt="picture1"></img>
</div>
<div className="userdiv-profile-name">
</div>
<div className="userdiv-profile-name">
Name:
</div>
<div className="userdiv-profile-name">
Driver ID:
</div>
<div className="userdiv-profile-name">
Plate Number:
</div>
<div className="userdiv-profile-name">
Status:
</div>
</div>
<div className="userdiv-stats">
Statistics
{driverstat.map((item, index) => {
return (
<li key={index} className={item.cName}>
{item.icon}
</li>
);
})}
<h4 class="view-history">View History</h4>
<input type="button" className="backtodrivers-btn" alt="back" value="Back"/>
</div>
</div>
<div className='mapdiv'>
<MapRender/>
</div>
</div>
<RechartBar/>
<RechartLine/>
</div>
);
}
export default Home;
The problem is It does run but it made my other elements go away because the map was rendered as seen in the last part of my MapRender.js, what I wanted to do is place this in a component and then call that component in my App.js (Similar to what I have done in RechartBar and RechartLine at the end of my App.js.
Thanks
You are replacing entire app with FinalMap component using this line.
Remove this line from MapRenderer.js
render(<FinalMap defaultZoom={12} places={places} />, document.getElementById('root'));
import React from 'react';
import { render } from 'react-dom';
import Map from './mapProps';
//import './style.css';
const googleMapsApiKey = "API_KEY";
export default function FinalMap(props) {
const {
places,
loadingElement,
containerElement,
mapElement,
defaultCenter,
defaultZoom
} = props;
return (
<Map
googleMapURL={
'https://maps.googleapis.com/maps/api/js?key=' +
googleMapsApiKey +
'&libraries=geometry,drawing,places'
}
markers={places}
loadingElement={loadingElement || <div style={{height: `100%`}}/>}
containerElement={containerElement || <div style={{height: "80vh"}}/>}
mapElement={mapElement || <div style={{height: `100%`}}/>}
defaultCenter={defaultCenter || {lat: 25.798939, lng: -80.291409}}
defaultZoom={defaultZoom || 13}
/>
);
};
Then in App.js
import React from 'react';
import picture1 from '../../src/picture1.jpg';
import RechartBar from '../postlist/Rechart-Bar';
import RechartLine from '../postlist/Rechart-Line';
import driverstat from '../driverprofiles/driverstat';
import AppMap from './Maps/map';
import MapRender from './Maps/MapRender';
function Home() {
return (
<div className="Bodydiv">
<div className="homediv">
<div className="userdiv">
<div className="userdiv-profile">
<div className="userdiv-profile-photo">
<img src={picture1} className="photo" alt="picture1"></img>
</div>
<div className="userdiv-profile-name">
</div>
<div className="userdiv-profile-name">
Name:
</div>
<div className="userdiv-profile-name">
Driver ID:
</div>
<div className="userdiv-profile-name">
Plate Number:
</div>
<div className="userdiv-profile-name">
Status:
</div>
</div>
<div className="userdiv-stats">
Statistics
{driverstat.map((item, index) => {
return (
<li key={index} className={item.cName}>
{item.icon}
</li>
);
})}
<h4 class="view-history">View History</h4>
<input type="button" className="backtodrivers-btn" alt="back" value="Back"/>
</div>
</div>
<div className='mapdiv'>
<MapRender places={[
{latitude:14.7539407,longitude:121.0338431},
{latitude: 14.625981794368357,longitude: 121.06170033978614},
]}/>
</div>
</div>
<RechartBar/>
<RechartLine/>
</div>
);
}
export default Home;

Setting background image as prop in react

I have a react component that needs to take in a background image from the parent Play component, not set in the stylesheet. I'm trying to pass it as a prop to the component, but not sure quite sure how to get this working:
Main component
import React from 'react'
import ReactDOM from 'react-dom'
import DeviceBlock from '/DeviceBlock/DeviceBlock'
const Play = {
init() {
const container = document.getElementById('blocker-container');
if(container) {
ReactDOM.render(
<DeviceBlock
backgroundImage={'background-image-url.png'}
logo={'url-to-logo.png'} />,
container
)
}
}
}
document.addEventListener('DOMContentLoaded', () => {
Play.init()
})
Blocking component imported into above Play component
import React from 'react'
import './DeviceBlock.scss'
function DeviceBlock (props) {
constructor(props) {
super(props)
this.state = {
backgroundImage: backgroundImage,
logo: logo;
}
}
return (
<div className='device-blocking' style={this.state.backgroundImage}>
<div className='container'>
<div className='logo'>
<img src='{{this.state.logo}}' />
</div>
<div className='message'>
<h1>Content</h1>
<a href='/' className='btn btn--primary btn--lg'>Link</a>
</div>
</div>
</div>
)
}
export default DeviceBlock
You should import your background img
import BackgroundImage from '...png'; // Relative Path to BackgroundImage
import Logo from '...png'; // Relative Path to Logo
and in your state
this.state = {
backgroundImage: `url(${BackgroundImage})`,
logo: Logo
};
Also I noticed that your <img> is wrong
<img src='{{this.state.logo}}' />
Should be
<img src={this.state.logo} />
Also note I saw that you added a constructor inside a function.
If you want to create a react component with state you need to make the component a class.
class DeviceBlock extends React.Component {
constructor(props) {
super(props);
this.state = {}
}
render() {
...
}
}
EDIT: This is the updated code for your edit based on passing through props.
import React from 'react'
import ReactDOM from 'react-dom'
import DeviceBlock from '/DeviceBlock/DeviceBlock'
import BackgroundImage from '../url-to-background.png'; // Path to BackgroundImage
import Logo from 'url-to-logo.png'; // Relative Path to Logo
const Play = {
init() {
const container = document.getElementById('blocker-container');
if (container) {
ReactDOM.render(
<DeviceBlock
backgroundImage={BackgroundImage}
logo={Logo}
/>,
container
)
}
}
}
document.addEventListener('DOMContentLoaded', () => {
Play.init()
})
import * as React from 'react'
import './DeviceBlock.scss'
function DeviceBlock (props) {
return (
<div
className='device-blocking'
style={{ backgroundImage: `url(${props.backgroundImage})` }}
>
<div className='container'>
<div className='logo'>
<img src={props.logo} />
</div>
<div className='message'>
<h1>Content</h1>
<a href='/' className='btn btn--primary btn--lg'>Link</a>
</div>
</div>
</div>
);
}
export default DeviceBlock
Note my solution only works if your images are from your own server and processed from webpack and not from another URL.
If the images are from another URL you shouldn't import the URLs and add them directly to the props
<DeviceBlock
backgroundImage="url-to-background.png",
logo="url-to-logo.png"
/>
Style is an object. Try it like this:
style={{backgroundImage: this.state.backgroundImage}}
Further, you cannot have a constructor and use state within a functional component. Either turn your component into a regular react component and keep the state, or have the state part in a regular react component and pass it down as props into the functional component. This is also mentioned in the answer by #Kenneth Truong
To turn it into a regular react component you can do the following:
class DeviceBlock extends React.Component {
constructor(props) {
super(props)
this.state = {
backgroundImage: "url('url-to-background.png')",
logo: "url('url-to-logo.png')";
}
}
render() {
return (
<div className='device-blocking' style={{backgroundImage: this.state.backgroundImage}}>
<div className='container'>
<div className='logo'>
<img src='{{this.state.logo}}' />
</div>
<div className='message'>
<h1>Content</h1>
<a href='/' className='btn btn--primary btn--lg'>Link</a>
</div>
</div>
</div>
)
}
}
You can see it working here:
https://codepen.io/anon/pen/zWexzO
UPDATE
Based on the updated question, you can also keep it as a functional component and pass down props:
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
backgroundImage: "url('url-to-background.png')",
logo: "url('url-to-logo.png')";
}
}
render() {
return (
<DeviceBlock
backgroundImage={this.state.backgroundImage}
logo={this.state.logo}/>
)
}
}
const DeviceBlock = (props) => {
return (
<div className='device-blocking' style={{backgroundImage: props.backgroundImage}}>
<div className='container'>
<div className='logo'>
<img src='{{props.logo}}' />
</div>
<div className='message'>
<h1>Content</h1>
<a href='/' className='btn btn--primary btn--lg'>Link</a>
</div>
</div>
</div>
)
}
https://codepen.io/anon/pen/OvdPOQ
The app component is simply demonstrating that you can pass down some dynamic state. You can, of course, render the DeviceBlock component directly from your Play.init function like you do in your provided code (then you can just ignore the App component part).
I was able to get the images to show in the child component by passing the images into <DeviceBlock /> in the parent like so:
<DeviceBlock
backgroundImage="background-image-url.png"
logo="logo-image-url.png" />,
container
and then taking them as props in the child
<div className='device-blocking' style={{ backgroundImage: `url(${props.backgroundImage})` }}>
<div className='container'>
<div className='logo'>
<img src={props.logo} />
</div>
<div className='message'>
<h1>Content</h1>
<a href='/' className='btn btn--primary btn--lg'>Link text</a>
</div>
</div>
</div>

Why is my component not effectively receiving props?

I keep getting a message that the item I'm trying to access via props is undefined. Can you please tell me why it's not working?
Here is where the instance where the props are attempting to be passed... I'm specifically talking about the tellus and yourTrial props.
import React from 'react'
import Info from './components/Info'
import Upsell from '../../../general/components/order/components/Upsell'
import FormTwo from '../../../general/components/forms/FormTwo'
import Footer from '../../../cbd-desktop/components/layout/Footer'
export default class Order extends React.Component {
render() {
return (
<div>
<div>
<div style={styles.header}>
<img style={styles.leaf} src="./resources/desktop-img/leaves_top.png" />
<img style={styles.logo} src="./resources/desktop-img/logo_white.png" />
</div>
<div style={styles.wrapper}>
<div style={styles.leftWrapper}>
<Info />
<Upsell styles={upsellStyles} />
</div>
<FormTwo styles={formStyles} tellus="Tell us where to send" yourTrial="YOUR TRIAL BOTTLE"} />
</div>
</div>
<Footer style={styles.footer}/>
</div>
)
}
}
And here is where I am trying to display these values on the child... towards the top in two h2s
import React from 'react'
import { connect } from 'react-redux'
import { stepTwoSubmit, saveBillingData } from
'../../actions/formStepTwoActions'
import { addReceiptProduct } from '../../actions/receiptActions'
import FormTwoInputs from './components/FormTwoInputsComponent.jsx'
import Throbber from '../throbber/Throbber'
import FormWarning from './components/FormWarningComponent.jsx'
import Button from '../../../cbd-desktop/components/layout/Button'
const mapStateToProps = state => ({
state:state,
config:state.config,
downsellProduct:state.downsell.downsellProduct || {},
receiptProducts:state.receipt.receiptProducts || []
})
const mapDispatchToProps = {
stepTwoSubmit,
saveBillingData,
addReceiptProduct
}
#connect(mapStateToProps, mapDispatchToProps)
export default class FormTwo extends React.Component {
constructor(props) {
super(props)
componentWillReceiveProps(nextProps) {
let formTwoResponse = nextProps.state.stepTwo.formTwoResponse
this.checkOrderStatus(formTwoResponse)
}
componentDidMount() {
this.fillMainOrder()
this.calculateViewers()
this.calculateTimer()
}
render() {
let { state, props, inputs, onInputFocus, saveInputVal, styles } = this,
CustomTag = props.labels ? 'label' : 'span',
{ submitting, formWarning } = state,
{ invalidInputID, text, visible } = formWarning
return (
<div style={styles.formWrapper}>
<p style={styles.yellowBanner}>{this.state.viewers} people viewing this product right now</p>
<div style={styles.formInnerWrapper}>
<div style={styles.headerWrapper}>
<h2 style={styles.header}>{this.props.tellus}</h2>
<h2 style={styles.header}>{this.props.yourTrial}</h2>
</div>
<div style={styles.weAccept}>
<p style={styles.weAcceptText}>We Accept:</p>
<img style ={styles.cardImage} src="resources/desktop-img/cards.png" />
</div>
<form onSubmit={this.submit}>
<FormTwoInputs onInputFocus={onInputFocus} saveInputVal={saveInputVal} CustomTag={CustomTag} styles={styles} />
<FormWarning visible={visible} invalidInputID={invalidInputID} text={text} />
<Button style={styles.button} buttonText="RUSH MY TRIAL" />
</form>
</div>
<img src="resources/desktop-img/secure.png" />
<div style={styles.urgencyWrapper}>
<div style={styles.urgencyTextWrapper}>
<span style={styles.redText}>{this.state.viewers} people are viewing this offer right now -</span>
<span style={styles.blueText}>{this.state.counter}</span>
</div>
<p style={styles.blueText}>Claim Your Bottle Now</p>
</div>
<Throbber throbberText='Confirming your shipment...' showThrobber={submitting} />
</div>
)
}
}

Resources