Make component draggable using react-dnd - javascript

I'm trying to drag a component using react-dnd
I would try to make like this example but only dragging for the moment.
In my app on top of all component I import react-dnd-html5-backend and wrap my app:
import Backend from 'react-dnd-html5-backend'
import { DndProvider } from 'react-dnd'
render(
<Provider store={store}>
<FluentuiProvider theme={themes.teams}>
<DndProvider backend={Backend}>
<App theme={themes.teams} />
</DndProvider>
</FluentuiProvider>
</Provider>,
document.getElementById('root')
)
Then in my component:
import { useDrag } from 'react-dnd';
export default ({ call, pauseCall, onHoldCalls, endCall, addNote }) => {
const [collectedProps, drag] = useDrag({
item: { type: 'Personna' },
})
return (
<div className="personna">
<Persona ref={drag} {...call.CALL_DETAILS.personInfos["formattedPersData"]} size={PersonaSize.size40} />
</div>
)
}
When I render the component I get this error
TypeError: node.setAttribute is not a function
at HTML5Backend.connectDragSource (HTML5Backend.js:487)
at SourceConnector.reconnectDragSource (SourceConnector.js:115)
I haven't added a dragSource because in example it's not used.
I don't know why I'm getting this error message.

As #Panther said, the ref should be placed on a HTML element, not a React Component:
return <div ref={drag}>{"Drag me!"}</div>;
Or, in your case, you could add the ref to the <div className="personna"> container:
return (
<div ref={drag} className="personna">
<Persona ....
To help you get to the minimal drag example, take a look at this very minimal setup:
App.js
import React from "react";
import Backend from "react-dnd-html5-backend";
import { DndProvider } from "react-dnd";
import { MyComponent } from "./MyComponent";
import "./styles.css";
export default function App() {
return (
<DndProvider backend={Backend}>
<div className="App">
<MyComponent />
</div>
</DndProvider>
);
}
MyComponent.js
export default function App() {
return (
<DndProvider backend={Backend}>
<div className="App">
<MyComponent />
</div>
</DndProvider>
);
}
Try it on codesandbox.io!

Related

How to render my home component in the app.js file?

I am trying to render my home component in the App.js like this: export function App() { return ( < Home /> ) }
but It does not display my content. Why is that?
I am not receiving any errors.
You can import and call the component like I have mentioned below,
App.js
import './App.css';
import Home from './Components/Home'
function App() {
return (
<div className="App">
<Home />
</div>
);
}
export default App;

next js - how to create hoc for the page

When I use the code below, I've got the error
Error: The default export is not a React Component in page: "/"
pages/index.tsx
import React, { useState, useRef } from "react";
import type { NextPage } from "next";
import WithToast from "hoc/WithToast/WithToast";
const Home: NextPage = () => {
return (
<div>
Home
</div>
);
};
export default WithToast(Home);
WithToast.tsx
import React from "react";
import { ToastContainer, Zoom } from "react-toastify";
import { NextComponentType, NextPageContext } from "next";
function WithToast(Component: NextComponentType<NextPageContext, any, {}>) {
return (
<div className="with-toast">
<ToastContainer
transition={Zoom}
position="top-center"
autoClose={200}
hideProgressBar={true}
draggable={false}
closeButton={false}
/>
{Component}
</div>
);
}
export default WithToast;
You should call the wrapped Component like this:
function withToast(Component: NextComponentType<NextPageContext, any, {}>) {
return (
<div className="with-toast">
<ToastContainer
transition={Zoom}
position="top-center"
autoClose={200}
hideProgressBar={true}
draggable={false}
closeButton={false}
/>
<Component />
</div>
);
}
or like this:
function withToast(component: NextComponentType<NextPageContext, any, {}>) {
return (
<div className="with-toast">
<ToastContainer
transition={Zoom}
position="top-center"
autoClose={200}
hideProgressBar={true}
draggable={false}
closeButton={false}
/>
{component()}
</div>
);
}
Or you are basically trying to render a function object in JSX as a child, and that throws an exception.
The HOC names should not begin with a capital case character.
That NextJS error should just be due to the fact you had that error that was not catched during SS render.

TypeError: render is not a function updateContextConsumer

I'm new at ReactJs and trying to learn ContextAPI but I'm having this error.I read titles about this situation but I can't reach to solution.Firstly I tried to re-install react as a old version but it didn't changed.I tried to wrap App inside of app.js instead of index.js but I had same result as it happens right now.
App.js
import React, { Component } from 'react'
import './App.css';
import UserFinding from './components/UserFinding';
class App extends Component {
render() {
return (
<div>
<UserFinding/>
</div>
)
}
}
export default App;
UserFinding.js
import React, { Component } from 'react'
import User from './User.js'
import UserConsumer from '../context.js'
export default class UserFinding extends Component {
render(){
return(
<UserConsumer>
{value=>{
const users=value;
return(
<div>
{
users.map(user=>{
return(
<User key={user.id} id={user.id} userName=
{user.userName} department={user.department}/>
)
}
)
}
</div>
)
}}
</UserConsumer>
)
}
}
User.js
import React, { Component } from 'react'
export default class User extends Component {
state={
isVisible:true
}
hideShowCard=()=>{
this.setState({
isVisible:!this.state.isVisible
})
}
deleteOnUser=()=>{
//Dispatch
}
render() {
return (
<div>
<div className="row">
<div className="col-sm-6">
<div className="card">
<div className="card-body">
<h5 className="card-title">{this.props.userName}<i onClick=
{this.deleteOnUser} className="fa fa-trash ml-2"></i></h5>
{this.state.isVisible ? <p className="card-text">
{this.props.department}</p>:null}
<div onClick={this.hideShowCard} className="btn btn-primary">
{this.state.isVisible ? "Hide" : "Show"}</div>
</div>
</div>
</div>
</div>
</div>
)
}
}
context.js
import React,{Component} from 'react';
const UserContext=React.createContext();
export class UserProvider extends Component {
state={
users:[
{
id:1,
userName:"Ufuk Oral",
department:"Software Engineering"
},
{
id:2,
userName:"Emre Çorbacı",
department:"Data Science"
}
]
}
render(){
return (
<UserContext.Provider value={this.state}>
{this.props.children}
</UserContext.Provider>
)
}
}
const UserConsumer=UserContext.Consumer;
export default UserConsumer;
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import UserProvider from './context.js';
ReactDOM.render(
<UserProvider><App/></UserProvider>,document.getElementById('root'));
serviceWorker.unregister();
these are my codes.
It looks like you are exporting and importing the content in context.js file wrong.
Instead of
import UserProvider from './context.js';
try something like this
import {UserProvider} from './context.js';
And how did you try to upgrade the react version? are you using create-react-app? if so you will have to update the react scripts as well. To upgrade to selected version you have to try something like this
npm install --save --save-exact react#x.xx react-dom#x.xx
or
yarn add --exact react#x.xx react-dom#x.xx
I am facing this problem when 'provider' is not added in the context component.
such that,
<AuthContext value={allContexts}>
{children}
I solved it, just added '.Provider'
such that,`
<AuthContext.Provider value={allContexts}>
{children}
</AuthContext.Provider>`

How do I change the innerHTML of an element using React?

I want to change innerHTML of a div, when I click on the button. I don't know why, but instead of getting an error, or getting the expected result it deletes to content and replacing it with "[object Object]".
How can I get it work?
import React from 'react';
import Login from './components/login.js';
import SignIn from './components/signin';
import './App.css';
function App() {
function LoginOnClick(){
document.getElementById("wrapper").innerHTML = <SignIn />;
}
return (
<div className="container" id="wrapper">
<button onClick={LoginOnClick}>Login</button>
<Login />
</div>
);
}
export default App;
You can make use of Hooks (Added n React 16.8).
import React, {useState} from 'react';
import Login from './components/login.js';
import SignIn from './components/signin';
import './App.css';
function App() {
const [signIn, setSignIn] = useState(false);
return (
<div className="container" id="wrapper">
{signIn ? <SignIn /> : <> //This is React Fragments syntax
<button onClick={() => setSignIn(true)}>Login</button>
<Login />
</>
}
</div>
);
}
export default App;
With react you don’t have to set the innerHtml to do this, instead the more typical way is to have internal state in your component and conditionally render your SignIn component based off that. To use state the component either needs to be class or use hooks, classes are more traditional so I changed the component to be a class.
To make a class a react component you need to extend the class with the React.Component, this is because react components have lots of internal behaviours that you need to include with your class for it to be considered a component.
So
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
signIn: false,
};
this.LoginOnClick = () => {
this.setState({ signIn: true });
};
}
render() {
if (this.state.signIn) {
return (
<div className="container">
<SignIn />
</div>
);
}
return (
<div className=“container”>
<button onClick={this.LoginOnClick}>Login</button>
<Login />
</div>
);
}
}
Here is a simple way to do it:
import {useState} from "react";
const App = () => {
const [txt, setTxt] = useState("");
setTxt(<p> 'Lorem ipsum dummy text blabla.' </p>);
return(
<div>
{txt}
</div>
)
}
export default App;

Using react api context alongside react router

I have a problem with passing context to route. I get an error when i click a link that goes to my component where context was passed from App component. Below is that component with App (only one import just to show where Context is coming from):
App.js
import { Context } from './Context';
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
cryptolist: []
}
}
componentDidMount = () => {
fetch('https://api.coinmarketcap.com/v2/ticker/?structure=array')
.then(response => response.json())
.then(json => this.setState({
cryptolist: json.data
}))
}
render() {
return (
<div>
<Menu />
<Context.Provider value={this.state}>
<Userlist />
</Context.Provider>
</div>
)
}
}
export default App;
Userlist.js ( should be cryptolist or something )
import { Context } from '.././Context'
export default class Userlist extends Component {
render() {
return (
<main>
<Context.Consumer>
{(context) => context.cryptolist.map(el => {
return (
<div>
<h2>{el.name}</h2>
<h5>{el.symbol}</h5>
<h3>{el.quotes.USD.price}</h3>
</div>
)
})}
</Context.Consumer>
</main>
)
}
}
Context.js
import React from 'react';
export const Context = React.createContext();
Everything works just fine here untill i wanted to make a menu that links to this component.
import React from "react";
import { slide as Slider } from 'react-burger-menu';
import { BrowserRouter as Router, Route, Link, Switch} from "react-router-dom";
import Main from './main';
import Userlist from './userlist';
export default class Menu extends React.Component {
render () {
return (
<Router>
<div className="bg-navy w-100 h-100">
<Slider width={ 180 } isOpen={ false }>
<Link className="menu-item" to="/main">Home</Link>
<Link className="menu-item" to="/crypto">About</Link>
</Slider>
<Switch>
<Route path="/main" component={Main} />
<Route path="/crypto" component={Userlist} />
</Switch>
</div>
</Router>
);
}
}
When i click a link to component Userlist i get an error thats cryptolist is not defined. I get it that Userlist can't see a context after clicking link to it. How to pass it correctly?
You are using the routes in the Menu component. Is this really you want? Though, I don't know how this slide thingy works. Maybe this is the way you want to go. I think your problem occurs because your Menu component is not wrapped by the provider. Try like this:
<Context.Provider value={this.state}>
<Menu />
<Userlist />
</Context.Provider
Your Menu component will call Userlist but as it is out the Provider the context doesn’t exist!
Replace Userlist in Context.Provider by Menu and all will be fine.

Categories

Resources