React JS- not able to detect 'show' function - javascript

I am trying to build a simple click counter in which the counter will increase by 1(initially 0) with each click. But the error I am getting is 'show' is defined but never used.The function 'show' re-renders the DOM after each click as given in index.js file.
App.js file-
import './App.css';
import React, { Component } from 'react';
class App extends Component {
render() {
return (
<div onClick={this.props.onClick}>This div has been clicked {this.props.clicks} times.</div>
);
}
}
export default App;
index.js file-
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
let model = { clicks: 0 };
function show() {
ReactDOM.render(<App clicks={model.clicks} onClick={()=> { model.clicks += 1; show();}} />, document.getElementById('root'));
}
reportWebVitals();

Change your index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
class Index extends React.Component {
state = {
clicks: 0
};
render() {
return (
<App
clicks={this.state.clicks}
onClick={() => this.setState((props) => ({ clicks: props.clicks + 1 }))}
/>
);
}
}
ReactDOM.render(<Index />, document.getElementById("root"));
Codesandbox: https://codesandbox.io/s/dark-firefly-i30t5?file=/src/index.js

Related

React draft wysiwyg dropdown not working problem

Editor is working but dropdown not working,
toolbar image
import { useState } from 'react';
import { EditorState } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
const MyEditor = () => {
let editorState = EditorState.createEmpty();
const [description, setDescription] = useState(editorState);
const onEditorStateChange = (editorState) => {
setDescription(editorState);
};
return (
<div>
<Editor
editorState={description}
toolbarClassName="toolbarClassName"
wrapperClassName="wrapperClassName"
editorClassName="editorClassName"
onEditorStateChange={onEditorStateChange}
/>
</div>
);
};
export default MyEditor;
When clicking on the dropdown it shows following warning in console
Console image
Change your index.js
from
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
to
import React from "react";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { render } from "react-dom"; // add this
render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById("root")
);

How to render react class component with React HashRouter and Apollo client?

I am working at a project in which I must use only React class components and I am fetching data from an Apollo server.
The problem is that in Chrome is rendering only the Navbar.jsx. When I am navigating on one of the links nothing is on the screen. Also there is not any error in the console.
Could somebody help me?
Thanks!
This is Index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import {
ApolloClient,
InMemoryCache,
ApolloProvider,
} from "#apollo/client";
import { HashRouter } from 'react-router-dom';
export const client = new ApolloClient({
uri: ' http://localhost:4000/',
cache: new InMemoryCache()
});
ReactDOM.render(
<React.StrictMode>
<HashRouter >
<ApolloProvider client={client}>
<App />
</ApolloProvider>
</HashRouter>
</React.StrictMode>,
document.getElementById('root')
);
reportWebVitals();
Here is App.js :
import React, { Component } from 'react'
import './App.css';
import { Switch, Route} from 'react-router-dom'
import Navbar from './Components/Navbar';
import Bikes from './Pages/Bikes';
import Books from './Pages/Books';
import { client } from './index';
import {GET_QUERY} from './GraphQl/Queries'
class App extends Component {
state={
currencies: [],
}
componentDidMount = async ()=>{
const response = await client.query({
query:GET_QUERY
})
this.setState({
currencies:response.data.currencies
})
}
render() {
return (
<div className="App">
<Navbar currencies={this.state.currencies}/>
<Switch>
<Route exact path="/bikes" component={Bikes} />
<Route exact path="/books" component={Books} />;
</Switch>
</div>
);
}
}
export default App;
Here is Navbar.jsx :
import React, { Component } from 'react'
import {Link} from 'react-router-dom'
import styled from 'styled-components'
import { withRouter } from 'react-router';
const StyledLink = styled(Link)`
`;
class Navbar extends Component {
render() {
return (
<nav>
<div>
<ul>
<li>
<StyledLink to="/bikes" replace>Bikes</StyledLink>
</li>
<li>
<StyledLink to="/books" replace>Books</StyledLink>
</li>
</ul>
</div>
</nav>
)
}
}
export default withRouter(Navbar)
and one of the pages, Bikes.jsx:
import React, { Component } from 'react'
import { client } from '../index'
import { GET_QUERY } from '../GraphQl/Queries'
import { CATEGORY_VAR } from '../GraphQl/Variables'
class Bikes extends Component {
state={
bikesArt: []
}
componentDidMount = async ()=>{
const response = await client.query({
query: GET_QUERY,
variables: CATEGORY_VAR
})
this.setState({
bikesArt:response.data.category.products
})
}
render() {
return (
<div>
<h1>Bikes</h1>
</div>
)
}
}
export default Bikes
Solved it. It was the CSS. The navbar was covering the only <h2> tag from the page

Class constructor not getting called

I have a function ChartWrapper and a class called LineChart.
All the code:
index.js ->
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
serviceWorker.unregister();
App.js ->
import React, {useRef, useEffect, useState, Component} from 'react';
import './App.css';
import ChartWrapper from './ChartWrapper'
class App extends Component {
render() {
return (
<div id="app">
<ChartWrapper />
</div>
)
}
}
export default App;
ChartWrapper.js ->
import React, {Component, useEffect} from 'react';
import { useRef } from 'react';
import LineChart from './LineChart'
function ChartWrapper() {
const svgRef = useRef();
console.log("works");
useEffect( () => {
const chart = <LineChart parent = {svgRef} />
console.log(chart);
}, []);
return (
<svg ref={svgRef}>
</svg>
);
}
export default ChartWrapper;
LineChart.js ->
import React, {Component} from 'react'
import {scaleLinear} from 'd3-scale'
import {max} from 'd3-array'
import {select} from 'd3-selection'
class LineChart extends Component {
constructor (props) {
super(props);
this.svg = select(props.parent);
console.log("does this work");
console.log(this.svg);
}
}
export default LineChart;
The ChartWrapper function creates a LineChart object and passes a const as a prop. To check if the code is working, I have print statements. For some reason, the print statements in ChartWrapper work fine. The print statements in LineChart constructor class however do not.
Am I missing something?
What you get in return when you log chart to the console is just an object representing the component, like this:
If you look at the type, it specifies the function/class to call. The class is only instantiated when it's rendered.
And the chart component is not returned, therefore react does not render it.
you need to call the render method for LineChart

React.js TypeError: Object(...) is not a function

I'm developing an app fetching api and displaiy it using ReactJS, My index.js file is:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './components/App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render( < App /> , document.getElementById('root'));
registerServiceWorker();
the error is
TypeError:
Object(...) is not a function
in Module../src/index.js
how do I solve this? Thanks!
My App.js code is here
import React, {
Component
} from 'react';
import PokeList from './PokeList';
import './styles/App.css';
class App extends Component {
constructor() {
super();
this.state = {};
}
render() {
return ( <div className = "App" >
<PokeList />
</div>
);
}
}
export default App;
PokeList.js
import React from 'react';
import './styles/PokeList.css';
const PokeList = () => {
return ( <section className = "poke-list" >
</section>
)
}
export default PokeList;
I think You just need to upgrade to react > 16.8. There are no breaking changes in regards to react, so you should be fine.

React-Router v4.2.2 not working (I think I've done something wrong in the Route tag?)

I'm using react-router v4.2.2 in my project, and am trying to create a set of cards that each link to other components. Right now I'm just testing that the router works, by routing each Card to one specific component called 'Project1'. This, however, is not working; I'm not seeing the div inside the Project1 component pop up. What am I doing wrong?? Shouldn't each Card link to the Project1 component?
Here is the code for the main container that holds the cards:
import React from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import ProjectCard from '../components/project_card.js';
import Project1 from '../components/project1.js';
class ProjectCards extends React.Component {
render() {
var projectCards = this.props.projects.map((project, i) => {
return (
<div key={i}>
<Link to={`/${project.title}`}>
<ProjectCard title={project.title} date={project.date} focus={project.focus}/>
</Link>
</div>
);
});
return (
<div>{projectCards}</div>
);
}
}
function mapStateToProps(state) {
return {
projects: state.projects
};
}
export default connect(mapStateToProps)(ProjectCards);
Here is the code for the Routes container:
import React from 'react';
import Project1 from '../components/project1.js';
import { connect } from 'react-redux';
import { Route, Switch } from 'react-router-dom';
class Routes extends React.Component{
render() {
var createRoutes = this.props.projects.map((project, i) => {
return <Route key={i} exact path={`/${project.title}`} component={Project1}/>
});
return (
<Switch>
{createRoutes}
</Switch>
);
}
}
function mapStateToProps(state) {
return {
projects: state.projects
};
}
export default connect(mapStateToProps)(Routes);
Here is the code for the index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { applyMiddleware, createStore } from 'redux';
import ReduxPromise from 'redux-promise';
import { BrowserRouter } from 'react-router-dom';
import App from './components/App.jsx';
import css from '../style/style.css';
import style from '../style/style.css';
import reducers from './reducers';
const createStoreWithMiddleware = applyMiddleware(ReduxPromise)(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
, document.getElementById('root'));
and the code for Project1, which should display when a Card has been clicked:
import React from 'react';
const Project1 = () => {
return (
<div>hello there this is Project1</div>
);
}
export default Project1;
When you click on a link, you navigate to Project1, which has no Routes defined. You basically destroy your Route when you lick on it because the Switch is in the same component as the Link. The Switch statement needs to be moved to a 3rd component so that it still exists after clicking on a linking card.

Categories