HelpHelp to debug my React Code - reactjs

First of all, I want to ask whether is my statement is correct :
"When we are making components, it is better to put it in different files"
Is it correct? since currently I tried so, and it cause problems.
Parents :
import React, { Component } from 'react';
import './App.css';
import {SubmitComponent} from './submitComponent.jsx';
import {topicTable} from './topicTable.jsx';
// import {TopicsContainer} from './TopicsContainer.js'
const dashboardStyle = {
border: '2px solid black',
width: '70%',
height: 'auto',
marginLeft: 'auto',
marginRight: 'auto',
marginBottom: '100px',
};
class AppDashBoard extends Component {
constructor(props) {
super(props);
this.state = {
datas: []
}
}
submitTopic = (data) => {
console.log(data);
console.log(this.state.datas);
console.log(this.state.datas.concat([data]));
this.setState({
datas: this.state.datas.concat(data)
});
console.log(this.state.datas);
}
render() {
return (
<div style={dashboardStyle}>
<h1 style={{textAlign:'center'}}>Coding Exercise</h1>
<hr />
<SubmitComponent submitTopic={this.submitTopic} />
<topicTable topics={this.state.datas} />
</div>
);
}
}
export default AppDashBoard
and this is the topicTable component :
import React, {Component} from 'react';
import {oneTopic} from './oneTopic.jsx';
export class topicTable extends Component {
render() {
const topicstable = this.props.topics.map((topic) => (
<oneTopic
title={topic.title}
desc = {topic.desc}
vote = {topic.vote}
/>
));
console.log("HAHAHAHA");
return (
<div id="topics">
{oneTopic}
</div>
);
}
}
and Lastly, my oneTopic component:
import React, {Component} from 'react';
export class oneTopic extends Component {
render() {
return(
<div style={{width:'96%', height:300, backgroundColor :'#AAA'}}>
<h1>HAHAHAHA</h1>
</div>
);
}
}
My problems are :
1) In the topicTable component, the console.log("HAHAHA") is not executed at all, I wonder why ?
2) Also for the oneTopic, the HAHAHA is not showing at all.
Even I already export and import everything
Please help

ReactJS component names must begin with capital letters.
1) rename oneTopic to OneTopic
2) change {oneTopic} to <oneTopic />

Related

Minified React Error #130 Encountered, doesn't seem import-related?

The minified react error instructs me that an "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined."
Looking around, it seems that most people have issues with import/exports and the use of braces when necessary, eg. while using the default keyword.
However, this doesn't seem to be the issue here, which leaves me befuddled.
I have a few components in my program I've included below. None of these seem to strike me as improper importing or importing an undefined element.
How would I go about debugging this? If this is not import related, would it be dependency-related?
Code for reference below:
ExerciseDay:
import React from 'react';
import ExerciseItem from './ExerciseRoutine';
import ProgressionChart from "./ProgressionChart";
import surveyHelp from '../img/chart-help.png';
import surveyHelpText from '../questionnaire/chart-help.json';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group';
export default class ExerciseDay extends React.Component {
constructor() {
super();
this.state = {help: false, visibility: true};
const experience = localStorage["experience"];
const pageChosen = sessionStorage.getItem("page");
this.numeric = pageChosen ? sessionStorage["page"] : experience === "No" ? "29" : experience === "Yes, once" ? "30" : "31";
this.sheikoData = require("../programs/Sheiko" + this.numeric + ".json");
}
render() {
let exerciseRoutines;
if (this.sheikoData) {
exerciseRoutines = this.sheikoData.map(exerciseDay => {
return (<ExerciseItem key={exerciseDay.day} exerciseDay={exerciseDay}/>);
});
}
return (
<div className="ExerciseDay">
<div style={{textAlign: "center", fontFamily: "Spectral SC", fontSize: 60}}>
Sheiko {!this.numeric.includes('-') ? '#' : null}{this.numeric}</div>
<ProgressionChart data={this.sheikoData}/>
<div className="Survey-help" style={{marginLeft: "5%"}}>
<img id="help-button" src={surveyHelp} alt=""
style={{width: "2%", float: "left", borderRadius: "5px", background: "lightgreen"}}
onClick={() => {
this.setState({help: !this.state.help})
}}/>
<ReactCSSTransitionGroup transitionName="fade" transitionEnterTimeout={300}
transitionLeaveTimeout={500}>
<p style={{
marginLeft: "5%",
fontFamily: "Itim, cursive",
fontSize: 22
}}>{this.state.help ? surveyHelpText.text : null}</p>
</ReactCSSTransitionGroup>
</div>
{exerciseRoutines}
</div>
);
}
}
ExerciseRoutine:
import React from "react";
import ExerciseType from "./ExerciseType";
import show from '../img/show.png';
import hide from '../img/hide.png';
export default class ExerciseRoutine extends React.Component {
constructor() {
super();
this.state = {showExerciseType: true};
}
render() {
let exerciseRoutine;
if (this.props.exerciseDay.routine) {
let routineKey = 0;
exerciseRoutine = this.props.exerciseDay.routine.map(routine => {
return <ExerciseType key={routine.exercise + routineKey++} routine={routine}/>
});
}
return (
<div className="ExerciseRoutine" style={{marginLeft: "15%"}}>
<div>
<h2 style={{
fontFamily: "Arima Madurai, cursive",
fontSize: 30,
display: "inline"
}}>{this.props.exerciseDay.day}
- {this.props.exerciseDay.routine.length} exercises</h2>
<img src={this.state.showExerciseType ? hide : show}
style={{width: this.state.showExerciseType? "2%": "2%", transform: "translateY(22%)"}} alt=""
onClick={() => this.setState({showExerciseType: !this.state.showExerciseType})}/>
</div>
<hr/>
{this.state.showExerciseType ? exerciseRoutine : null}
<br/>
</div>
)
}
}
ExerciseSelector:
import React from "react";
import Select from 'react-select';
import selection from "../programs/SheikoSelector.json";
export default class ExerciseSelector extends React.Component {
render() {
function logChange(val) {
if(!val) return;
sessionStorage["page"] = val.value;
window.location.reload();
}
return (
<Select name="exercise-selector" value="Current" clearValueText="yes"
options={selection} onChange={logChange} autofocus={true}
placeholder="Click here to search Sheiko program..."/>
);
}
}
ExerciseTask:
import React from "react";
import ReactToolTip from 'react-tooltip'
export default class ExerciseTask extends React.Component {
render() {
const effort = this.props.task.effort !== 0 ? Math.round(this.props.task.effort * 100) + "%" : "a comfortable";
return (<li className="ExerciseTask">
{this.props.task.sets} Sets of {this.props.task.reps} reps at {effort} effort
<ReactToolTip/>
</li>);
}
}
and ExerciseType:
import React from 'react';
import ExerciseTask from "./ExerciseTask";
import benchpress from '../img/benchpress.png';
import squat from '../img/squat.png';
import flies from '../img/flies.png';
import abs from '../img/abs.png';
import pushup from '../img/pushup.png';
import other from '../img/other.png';
export default class ExerciseType extends React.Component {
render() {
let exerciseType;
if (this.props.routine.tasks) {
let taskKey = 0;
exerciseType = this.props.routine.tasks.map(task => {
return <ExerciseTask key={taskKey++} task={task}/>
});
}
function determineImage(exercise) {
return exercise.includes("Bench") ? benchpress : exercise.includes("Squat") ? squat : exercise.includes("Fly") ? flies : exercise.includes("Abs") ? abs : exercise.includes("Push up") ? pushup : other;
}
return (<div className="ExerciseType" style={{backgroundColor: "#f9fbff"}}>
<h3 style={{
fontFamily: "Arima Madurai, cursive",
fontSize: 23
}}>{this.props.routine.exercise.charAt(0).toUpperCase() + this.props.routine.exercise.slice(1)}</h3>
<div style={{float: "left", whiteSpace: "nowrap"}}>
{exerciseType}
</div>
<img id="exercise-picture" src={determineImage(this.props.routine.exercise)}
data-tip={this.props.routine.exercise} alt=""/>
</div>);
}
}

I dont know how to fix useSprint using class

I received this error :
Line 21:28: React Hook "useSpring" cannot be called in a class component. React Hooks must be called in a React function component or a custom React Hook function react-hooks/rules-of-hooks.
I want to make a transition with the opacity and when I click the button appears the image or disappears.
import React, { Component } from 'react';
import { withTranslation } from 'react-i18next';
import { useSpring, config, animated } from "react-spring";
import './Experience.css';
class Experience extends Component {
constructor(props) {
super(props);
this.state = {
showA: false
};
}
render() {
// const [showA, setShowA] = useState(false);
const fadeStyles = useSpring({
config: { ...config.molasses },
from: { opacity: 0 },
to: {
opacity: this.state.showA ? 1 : 0
},
});
return (
<div style={{ padding: "15px" }} className="App">
<h2>Fade Demo</h2>
<div>
<animated.div style={fadeStyles}>
<img src={`https://a.wattpad.com/useravatar/valery2080.256.603024.jpg)`} alt="hola"/>
</animated.div>
<br />
<button onClick={() => this.setState(val => !val)}>Toggle</button>
</div>
</div>
);
}
}
export default withTranslation()(Experience);
You need to convert the class component to a functional component. Following is the implementation of Experience Component to a functional component.
Note: Make sure to add the CSS file in your implementation.
Following is the codesandbox link for your reference: https://codesandbox.io/s/jolly-wescoff-bnqm4
import React, { useState, Component } from "react";
import { withTranslation } from "react-i18next";
import { useSpring, config, animated } from "react-spring";
const Experience = () => {
const [showA, setShowA] = useState(false);
const fadeStyles = useSpring({
config: { ...config.molasses },
from: { opacity: 0 },
to: {
opacity: showA ? 1 : 0
}
});
return (
<div style={{ padding: "15px" }} className="App">
<h2>Fade Demo</h2>
<div>
<animated.div style={fadeStyles}>
<img
src={`https://a.wattpad.com/useravatar/valery2080.256.603024.jpg)`}
alt="hola"
/>
</animated.div>
<br />
<button onClick={() => setShowA(!showA)}>Toggle</button>
</div>
</div>
);
};
export default withTranslation()(Experience);

./activetenant' does not contain an export named 'ActiveTenant'

I am trying to use a component that is already created, but I cant figure out what the problem is:
activetenant
import React, { Component } from 'react';
import authAction from '../../redux/auth/actions';
class ActiveTenant extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div></div>
);
}
}
export default ActiveTenant;
and the component where I am trying to use it
import React, { Component } from "react";
import { connect } from "react-redux";
import { Layout } from "antd";
import appActions from "../../redux/app/actions";
import TopbarUser from "./topbarUser";
import TopbarWrapper from "./topbar.style";
import themes from "../../settings/themes";
import { themeConfig } from "../../settings";
import { ActiveTenant } from "./activetenant";
const { Header } = Layout;
const { toggleCollapsed } = appActions;
const customizedTheme = themes[themeConfig.theme];
class Topbar extends Component {
render() {
const { toggleCollapsed } = this.props;
const collapsed = this.props.collapsed && !this.props.openDrawer;
const styling = {
background: customizedTheme.backgroundColor,
position: "fixed",
width: "100%",
height: 70
};
return (
<TopbarWrapper>
<Header
style={styling}
className={
collapsed ? "isomorphicTopbar collapsed" : "isomorphicTopbar"
}
>
<div className="isoLeft">
<button
className={
collapsed ? "triggerBtn menuCollapsed" : "triggerBtn menuOpen"
}
style={{ color: customizedTheme.textColor }}
onClick={toggleCollapsed}
/>
</div>
<ul className="isoRight">
<li>
<ActiveTenant />
</li>
<li
onClick={() => this.setState({ selectedItem: "user" })}
className="isoUser"
>
<TopbarUser />
</li>
</ul>
</Header>
</TopbarWrapper>
);
}
}
export default connect(
state => ({
...state.App.toJS()
}),
{ toggleCollapsed }
)(Topbar);
And the error
./src/containers/Topbar/Topbar.js 105:34-46 './activetenant' does not
contain an export named 'ActiveTenant'.
You are use export default ActiveTenant In this case code should be like this
import ActiveTenant from "./activetenant";
If you want to export mulitple value then use {} to import
for example
//test.js
var a = "cool";
var b = "dool";
export a;
export b;
import {a,b} from './test.js'

componentDidMount() async background-image

React Newbee here
Firstly , I have a component DetailMovieCard.jsx where I am inserting background image in componentDidMount () It works fine but I was wondering is there any other efficient way instead of using
document.body.style.backgroundImage
DetailMovieCard.jsx
import React, { Component } from "react";
import { Row, Col, Glyphicon, Button } from "react-bootstrap";
import styled from "styled-components";
import { URL_IMAGE, URL_BACKGROUND } from "../const";
const Wrapper = styled.div`
max-width: 60%;
overflow: hidden; `;
const Image = styled.img`
float: left;
width: 40%;
`;
class DetailMovieCard extends Component {
componentDidUpdate() {
document.body.style.backgroundImage =
`url(${URL_BACKGROUND}${this.props.movie.backdrop_path})`;}
render() {
const {
poster_path, original_title, backdrop_path, tagline, overview,
} = this.props.movie;
return (
<Wrapper>
<Image alt="" src={`${URL_IMAGE}${poster_path}`} />
<div className="movie-details">
<h3>Title of the movie is {original_title} </h3>
<div>
<div className="movie-tagline"> {tagline} </div>
<div className="movie-overview">{overview} </div>
</div>
</div>
</Wrapper>
);
}
}
export default DetailMovieCard;
Secondly , I have a component called MovieDetails.jsx currently I am giving data fetched by componentDidMount() directly to <DetailMovieCard movie={this.state.movieData} > again it works fine but is there any better way of doing it ?
import React, { Component } from "react";
import axios from "axios";
import { URL_DETAIL, API_KEY } from "../const";
import DetailMovieCard from './DetailMovieCard';
import Header from './Header';
class MovieDetails extends Component {
constructor(props) {
super(props);
this.state = {
movieData: { movies: " " }
};
}
componentDidMount() {
const { id } = this.props.match.params;
axios.get(`${URL_DETAIL}${id}${API_KEY}&language=en-US&page=1`)
.then(response => {
this.setState({ movieData: response.data });
});}
render() {
return (
<div className= "movie-container">
<Header/>
<DetailMovieCard movie={this.state.movieData} />
</div>
);
}
}
export default MovieDetails;
You can always use callbacks:
Set the backgroundImage in your main App component there is no reason to use <body>
Keep the current backgroundImage url in main App component state or in redux store
Then you can set the backgroundImage url using regular javascript callbacks

Proper syntax for loading/exporting react components?

I'm new to reactjs and am unable to debug this error: Element type is invalid: expected a string or a class/function but got: undefined. You likely forgot to export your component from the file it's defined in. Check the render method of Map.
Here is the code:
Map.js
import React, { Component } from 'react'
import { GoogleMapLoader, GoogleMap, Marker } from 'react-google-maps'
class Map extends Component {
render(){
const mapContainer = <div style={{height: '100%', width: '100%'}}></div>
return (
<GoogleMapLoader
containerElement = { mapContainer }
googleMapElement = {
<GoogleMap
defaultZoom={15}
defaultCenter={this.props.center}
options={{streetViewControl: false, mapTypeControl: false}}>
</GoogleMap>
} />
)
}
}
export default Map
Places.js
import React, { Component } from 'react'
class Places extends Component {
render(){
return (
<div>
Helloljlk
</div>
)
}
}
export default Places
App.js:
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import Map from './components/Map'
import Places from './components/Places'
class App extends Component {
render(){
const location = {
lat: 40.7,
lng: -73.98
}
return (
<div>
Hello
<div style={{width: 300, height: 600, background: 'red'}}>
<Map center={location} />
</div>
<Places />
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'))
I've looked up similar issues but haven't been able to find anything that works i.e. removing {} from import statements.
The component GoogleMapLoader has been deprecated in the version 6 onwards (please refer to the changelog here). So if you are using that version, you will get undefined when you import GoogleMapLoader. Instead, you should now be using withGoogleMap.
Map.js
import React, { Component } from 'react'
import { GoogleMapLoader, GoogleMap, Marker } from 'react-google-maps'
const Map = withGoogleMap(props => (
<GoogleMap
defaultZoom={15}
defaultCenter={props.center}
options={{streetViewControl: false, mapTypeControl: false}} />
));
App.js
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import Map from './components/Map'
import Places from './components/Places'
class App extends Component {
render(){
const location = {
lat: 40.7,
lng: -73.98
}
const mapContainer = <div style={{height: '100%', width: '100%'}}></div>;
return (
<div>
Hello
<div style={{width: 300, height: 600, background: 'red'}}>
<Map
center={location}
containerElement={mapContainer}
/>
</div>
<Places />
</div>
)
}
}

Resources