I try to learn React JS, however, I stumbled over a problem I can't solve. I try to use an API to get a value of something and show the value as a simple text, but the text is not updating even tho the Data gets correctly log in console.
The Code of my App.js is
import React, { Component } from "react";
import { Button } from "#material-ui/core";
import { Image } from "react-bootstrap";
import albedo from "#albedo-link/intent/lib/albedo.intent";
import albedologo from "./albedo.png";
class LogInWithAlbedo extends Component {
constructor(props) {
super(props);
this.state = {
value: null
};
}
Albedo() {
albedo.publicKey({}).then((res) => {
const { intent, pubkey, signature, signed_message } = res;
console.log({ intent, pubkey, signature, signed_message });
this.setState((currentState) => {
return { value: pubkey };
});
});
}
render() {
const { pubkey } = this.state;
return (
<div>
<div>
<Button
style={{ width: "207px", height: "40px" }}
variant="contained"
color="default"
onClick={this.Albedo.bind(this)}
>
Login With <Image style={{ width: "55px" }} src={albedologo} />
</Button>
<h2>It is {pubkey}.</h2>
</div>
</div>
);
}
}
export default LogInWithAlbedo;
You can also see it here:
https://codesandbox.io/s/vigilant-star-ntqv7
Related
Component, myImage is never read.
import React from 'react';
import { Box } from "#mui/material";
import { Link } from 'react-router-dom';
import myImage from './Profile/Profile.myImage';
const HomeProfile = () => {
return (
<Box sx={{ border: '1px dashed grey' }}>
<myImage />
<Link to="/app/profile" className="red btn-flat white-text">
Change Profile
</Link>
</Box>
)
}
export default HomeProfile;
This is the file './Profile/Profile.myImage':
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchProfile } from '../../../actions';
import { Image } from 'react-bootstrap';
import axios from 'axios';
class myImage extends Component {
componentDidMount() {
this.props.fetchProfile();
}
async renderMyImage() {
const imageDir = await axios.get('/api/profile');
return (
<div>
<h1>hello</h1>
<Image src={imageDir.profileImg.type} />
</div>
);
}
render() {
return (
<div>
<div>{this.renderMyImage()}</div>
<h1>bye</h1>
</div>
);
}
}
function mapStateToProps({ user }) {
return { user };
}
export default connect(mapStateToProps, {fetchProfile})(myImage);
In the route.js, app.get('/api/profile') is defined like this.
however, nothing appears in the console.
app.get('/api/profile', requireLogin, async(req, res) => {
console.log('test: api/profile');
const profile = await User.find({ _user: req.user.id });
res.send(profile);
})
I thought, something was wrong in the function 'renderMyImage()', so I added "hello" and "bye", but still, nothing is on the view, while other components can be seen on the screen.
axios is async so renderMyImage should be an async function.
Have you tried
async renderMyImage() {
const imageDir = await axios.get('/api/profile');
return (
<div>
<h1>hello</h1>
<Image src={imageDir.profileImg.type} />
</div>
);
}
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);
I have created a function which fetches data from API and send a response of userDetail, which has been created in context. and function has been called in Dashboard component by importing context. And when user clicks button it render userData.
I am tried testing to check function has been called once or not, after click. but not able to achieve it.
Context Page
here userDataFunc is created .
import React, { Component, createContext } from "react";
import axios from "axios";
export const Contx = createContext();
export class ConProvider extends Component {
state = {
userData: []
};
userDataFunc = async () => {
await axios(`https://jsonplaceholder.typicode.com/users`)
.then((res) => {
if (res.status === 200) {
this.setState({
userData: res.data
});
}
})
.catch((err) =>
this.setState({
userDataerror: err
})
);
};
render() {
console.log(this.state.coin);
return (
<Contx.Provider
value={{
...this.state,
userDataFunc: this.userDataFunc
}}
>
{this.props.children}
</Contx.Provider>
);
}
}
Dashboard Component
Here Function and userdata state has been imported from context
import React, { useContext } from "react";
import { Contx } from "../ContextApi";
export default function Dashboard() {
const { userDataFunc, userData } = useContext(Contx);
return (
<div
style={{ height: "100vh", backgroundColor: "#151515" }}
className="d-flex justify-content-center align-items-center"
>
<button data-testid="renderData" onClick={userDataFunc}>
Render Data
</button>
<div
style={{
overflowY: "auto",
margin: "4px",
border: "2px solid",
padding: "12px",
height: "80vh"
}}
data-testid="tableData"
>
{userData.map((i) => {
return (
<h5 key={i.id} style={{ color: "#fff" }}>
{i.name}
</h5>
);
})}
</div>
</div>
);
}
Dashboard Test File
// import React from "react";
import { fireEvent, render } from "#testing-library/react";
import axiosMock from "axios";
import Dashboard from "./Dashboard";
import { Contx } from "../ContextApi";
jest.mock("axios");
it("Api Called", () => {
const { getByTestId } = render(
<Contx>
<Dashboard />
</Contx>
);
const renderButton = getByTestId("userData");
fireEvent.click(renderButton);
expect(Dashboard.userDataFunc()).toHaveBeenCalledTimes(1);
});
I use Two package
slate-react and emoji-mart
I want to when choose an Emoji , it puts on my editor.
import React from "react";
import { render } from "react-dom";
import { Editor } from "slate-react";
import { initialValue } from "./initialValue";
// Define our app...
class MyEditor extends React.Component {
// Set the initial value when the app is first constructed.
state = {
value: initialValue
};
// On change, update the app's React state with the new editor value.
onChange = ({ value }) => {
this.setState({ value });
};
onKeyDown = (event, change) => {
// This used to have stuff in it, but I moved it all to plugins.
};
clickMe=()=>{
this.setState({ value : this.state.value });
};
// Render the editor.
render() {
return (
<div>
<h1 onClick={this.clickMe}>Slate Editor Demo</h1>
<div style={{ border: "1px solid black", padding: "1em" }}>
<Editor
value={this.state.value}
onChange={this.onChange}
onKeyDown={this.onKeyDown}
renderNode={this.renderNode}
spellCheck={false}
/>
</div>
</div>
);
}
}
export default MyEditor;
import React,{useState} from 'react';
import 'emoji-mart/css/emoji-mart.css';
import { Picker } from 'emoji-mart';
function Emoji() {
const [emoji,setEmoji] = useState(null);
const addEmoji = (e) => {
setEmoji(e.native)
};
return <Picker onSelect={addEmoji} />
}
export default Emoji;
Try passing the editor ref to picker. Then in Emoji component in addEmoji method, try editorRef.current.InsertText(e.native). After hours of trying to solve this:
const YourTextEditor = props => {
const editor = createEditor();
const addEmoji = async emoji => {
await setTimeout(() => {
editor.focus();
}, 100);
editor.insertText(emoji.native);
};
return (
<>
<Editor
value={initialValue}
/>
<Emoji addEmoji={addEmoji} />
</>
);
};
const Emoji = props => {
return (<Picker onSelect={e => props.addEmoji(e)} />);
};
I'm using the official Semantic UI React components to create a web application. I have a form on a search page, which contains an input field.
import React from 'react'
import {Form} from "semantic-ui-react";
import RadiusOfSearchInput from "./RadiusOfSearchInput";
const NearbyShopsSearchForm = (props) => {
const { onSubmit, size, action, onChange, value, style } = props
return (
<Form onSubmit={onSubmit}>
<RadiusOfSearchInput size={size}
action={action}
onChange={onChange}
value={value}
style={style} />
</Form>
)
}
export default NearbyShopsSearchForm
The component that uses the form is as shown below:
import React, { Component } from 'react'
import {Menu, Container, Segment} from 'semantic-ui-react'
import ShopCardList from "../components/ShopCardList";
import axios from 'axios';
import NearbyShopsSearchForm from "../components/NearbyShopsSearchForm";
class NearbyShopsPage extends Component {
constructor(props) {
super(props)
this.state = {
radius: '',
shops: []
}
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleChange = (e, { value } ) => {
this.setState({ radius: value })
}
handleSubmit = (e, data) => {
const { radius } = this.state
const url = `/api/shops/#33.846978,-6.775816,${radius}`
axios.get(url)
.then((response) => {
this.setState({ shops: response.data })
})
.catch((error) => {
console.log(error)
})
e.preventDefault()
}
render() {
const { radius } = this.state
return (
<Segment basic>
<Menu fixed='top' size='huge' borderless>
<Menu.Item>
<NearbyShopsSearchForm onSubmit={this.handleSubmit}
size='large'
action={{ color: 'teal', content: 'Search', size: 'small' }}
onChange={this.handleChange}
value={radius}
style={{ width: '17.5em' }} />
</Menu.Item>
</Menu>
<Container style={{ marginTop: '5.5em' }}>
<ShopCardList shops={this.state.shops}/>
</Container>
</Segment>
)
}
}
export default NearbyShopsPage
I want to validate the form so it won't submit values other than decimals, which are valid values to represent a distance. I didn't find validation support in the SUIR official documentation. I'm aware of the redux-form possibility, but i fail to implement it correctly. what's the recommended and simplest way to implement the data validation feature?