I have try to upload image to Redux and show in of React-Konva in many ways. But it isn't work. Both in base64 and blob. But in normal situation like using component's state to keep data(base64) it's work. I don't know why.
In my component just have button for upload and React-Konva Component for show image
this is error from base64 store in redux and show to Image Tag
class UploadButton extends Component{
constructor(props){
...
this.handleUpload = this.handleUpload.bind(this);
}
handleUpload({target}){
const reader = new FileReader();
const file = target.files[0];
reader.onloadend = () => {
this.props.dispatch({
type: 'UPLOAD_IMAGE',
image: reader.result,
});
};
reader.readAsDataURL(file);
}
render(){
return(
<div>
<input
value="Upload"
type="button"
onClick={ () => { this.uploadInput.click() } }
/>
<input
id="inputUpload"
ref={ (ref) => { this.uploadInput = ref } }
type="file"
style={ { display: 'none' } }
onChange = { (event) => { this.handleUpload(event) }}
/>
</div>
);
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Stage, Layer, Image } from 'react-konva';
class ShowImage extends Component {
constructor(props){
super(props);
this.props = props;
this.state = {
image : null,
}
}
render(){
return (
<Stage
width={ 500 }
height={ 500 }
>
<Layer>
<Image image={ this.props.image} ></Image>
</Layer>
</Stage>
);
}
}
const mapStateToProps = ( state ) => ({
image : state.image,
});
export default connect(mapStateToProps)(ShowImage);
To use the image in react-konva you have to create a native instance of window.Image.
class VaderImage extends React.Component {
state = {
image: new window.Image()
};
componentDidMount() {
this.state.image.src = this.props.image;
this.state.image.onload = () => {
// need to update layer manually
this.imageNode.getLayer().batchDraw();
};
}
render() {
return (
<Image
image={this.state.image}
y={250}
ref={node => {
this.imageNode = node;
}}
/>
);
}
}
https://konvajs.github.io/docs/react/Images.html
Related
I'm also using semantic-ui-react. When I pass the child component down from the parent the css styling gets all messed up, I lose my images and the click doesn't work.
I can call the cardClickHandler method in the parent component and am console logging the correct child, i just can't get it to render (am not hitting the console.log in the child component).
I also tried to run the cardClickHandler method in the images container to pass it down but that didn't work.
please help and explain what i'm doing wrong. thanks!
images container:
import React from 'react';
import SearchBar from '../components/SearchBar';
import Images from '../components/Images';
import ImageCard from '../components/ImageCard';
class ImagesContainer extends React.Component {
state = {
images: [],
image: {},
sortValue: '',
inputValue: '',
};
componentDidMount() {
fetch('http://localhost:3000/images').then((resp) => resp.json()).then((resp) => {
this.setState({
images: resp
});
});
}
imageFilterOnChange = (event) => {
this.setState({
inputValue: event.target.value
});
};
sortImages = (images) => {
if (this.state.sortValue === 'location') {
return [ ...images ].sort((a, b) => {
if (a.location > b.location) {
return 1;
} else if (a.location < b.location) {
return -1;
} else {
return 0;
}
});
} else {
return images;
}
};
render() {
const filteredImages = this.state.images.filter((image) => {
return image.location.toLowerCase().includes(this.state.inputValue.toLowerCase());
});
return (
<div>
<Images
images={this.sortImages(filteredImages)}
onClick={this.cardClickHandler}
/>
<SearchBar
images={this.sortImages(filteredImages)}
imageFilterOnChange={this.imageFilterOnChange}
inputValue={this.state.inputValue}
onChange={this.handleSortImages}
/>
</div>
</div>
);
}
}
export default ImagesContainer;
parent component:
import React from 'react';
import ImageCard from './ImageCard';
import { Card, Image } from 'semantic-ui-react';
class Images extends React.Component {
state = {
image: []
};
cardClickHandler = (e) => {
let cardId = e.target.dataset.id;
this.props.images.find((image) => {
return image.id === cardId;
});
console.log('hi, cardId', cardId);
fetch(`http://localhost:3000/images/${cardId}`)
.then((resp) => resp.json())
.then((resp) => {
this.setState({
image: resp
})
console.log(this.state.image);
})
}
render() {
const allImages = this.props.images;
return allImages.map((image) => {
return (
<Card
key={image.id}
className="photo"
data-id={image.id}
data-name={image.name}
onClick={this.cardClickHandler}
>
<img
src={image.image}
alt=""
data-id={image.id}
data-name={image.name}
className="photo-image"
height={265}
/>
</Card>
);
});
}
}
export default Images;
child component:
i'm not hitting the console.log here, so no more code!
import React from 'react';
import { Card, Image } from 'semantic-ui-react';
class ImageCard extends React.Component {
render() {
console.log('image card');
return (
<Card>
</Card>
);
}
}
export default ImageCard;
I left a comment with a few improvements to the code you could make. Specifically:
You have an extra </div> in your ImagesContainer.
Also, you'll want to remove onClick={this.cardClickHandler} from ImagesContainer as cardClickHandler is defined not on ImagesContainer but instead on your Images component.
But the problem is that you are not rendering your ImageCard component at all. You are just rendering <Card> instead of <ImageCard>
Specifically, your parent component's render should change from this:
render() {
const allImages = this.props.images;
return allImages.map((image) => {
return (
<Card
key={image.id}
className="photo"
data-id={image.id}
data-name={image.name}
onClick={this.cardClickHandler}
>
<img
src={image.image}
alt=""
data-id={image.id}
data-name={image.name}
className="photo-image"
height={265}
/>
</Card>
);
});
}
to this:
render() {
const allImages = this.props.images;
return allImages.map((image) => {
return (
<ImageCard
key={image.id}
className="photo"
data-id={image.id}
data-name={image.name}
onClick={this.cardClickHandler}
>
<img
src={image.image}
alt=""
data-id={image.id}
data-name={image.name}
className="photo-image"
height={265}
/>
</ImageCard>
);
});
}
I have this component that loads an image and then only displays content after the image is loaded (checks for image loading state). How do a write a jest test to test that it is working properly and that the content only displays after the image has loaded and not before?
import HeaderImage from '../images/headerimage.svg';
const ImageStyled = styled.img`
margin-left: -0.1rem;
`;
export default class ImageDisplay extends Component {
constructor(props) {
super(props);
this.state = { imageStatus: 'loading' };
}
handleImageLoaded() {
this.setState({ imageStatus: 'loaded' });
}
renderContent = () => (
if (this.state.imageStatus === 'loading') {
return null;
}
else {
<div>
Some Sample Content
</div>
}
render() {
return (
<div>
<ImageStyled
src={HeaderImage}
onLoad={() => {
this.handleImageLoaded();
}}
/>
{this.renderContent()}
</div>
);
}
}
`
I know the title might be confusing, as well as might sound as a repeat, please read the whole description before marking it as repeat, I am new to react and need some help.
I am building a dashboard. I have a navigation bar div which has multiple tabs and a content div which has the corresponding content. Once a tab is clicked i render its corresponding content. Within any tab the user can do various things/changes. Lets say i have a tab ABC which when clicked produces an initial view, when i click this tab again when it is already clicked i need to re-render the ABC tabs content.
Essentially what i want to do is when after clicking test and test-demo once, user clicks test again the text 'test-demo' should disappear.
import React, { Component } from 'react';
const Button = (props) => {
return (
<button onClick={() => props.onClick(props.buttonName.trim())}>{props.buttonName}</button>
);
};
class Test extends Component {
static initialState = () => ({
appContent:null,
});
state = Test.initialState();
switchTab = (buttonKey) => {
this.setState(prevState => ({
appContent:<a>{buttonKey}</a>
}));
}
render() {
let appContent = null;
switch(this.props.navigationTab) {
case "test":
appContent = <Button onClick={this.switchTab} buttonName='test-demo' />
break;
default:
appContent = null
break;
};
return (
<div>
{appContent}
{this.state.appContent}
</div>
);
}
}
class AppContent extends Component {
render() {
return (
<div>
<Test navigationTab={this.props.navigationTab}/>
</div>
);
}
}
class App extends Component {
static initialState = () => ({
navigationTab:null,
});
state = App.initialState();
switchTab = (buttonKey) => {
this.setState(prevState => ({
navigationTab:buttonKey,
}));
}
render() {
return (
<div>
<div>
<Button onClick={this.switchTab} buttonName='test'/>
</div>
<AppContent navigationTab={this.state.navigationTab} />
</div>
);
}
}
export default App;
https://stackblitz.com/edit/react-fs8u7o?embed=1&file=index.js
import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
const Button = (props) => {
return (
<button onClick={() => props.onClick(props.buttonName.trim())}>{props.buttonName}</button>
);
};
class Test extends Component {
constructor(props) {
super(props);
this.state = {
appContent: null,
hideTestDemo:false,
};
}
componentWillReceiveProps(nextProps){
this.setState(prevState => ({
hideTestDemo:nextProps.hideTestDemo,
}));
}
switchTab = (buttonKey) => {
this.setState(prevState => ({
appContent: <a>{buttonKey}</a>,
hideTestDemo:false,
}));
}
render() {
let appContent = null;
switch (this.props.navigationTab) {
case "test":
appContent = <Button onClick={this.switchTab} buttonName='test-demo' />
break;
default:
appContent = null
break;
};
return (
<div>
{appContent}
{(!this.state.hideTestDemo ) ? this.state.appContent:null}
</div>
);
}
}
class AppContent extends Component {
render() {
return (
<div>
<Test {...this.props} />
</div>
);
}
}
class App extends Component {
constructor() {
super();
this.state = {
navigationTab: null,
};
}
hideTestDemo = false;
switchTab = (buttonKey) => {
if (this.hideTestDemo)
this.setState(prevState => ({
navigationTab: buttonKey,
hideTestDemo: true,
}));
else
this.setState(prevState => ({
navigationTab: buttonKey,
hideTestDemo:false,
}));
this.hideTestDemo=!this.hideTestDemo;
}
render() {
return (
<div>
<div>
<Button onClick={this.switchTab} buttonName='test' />
</div>
<AppContent {...this.state} />
</div>
);
}
}
render(<App />, document.getElementById('root'));
My card Component
<Card
image={card.flipped || card.discovered ? card.url : 'http://flotrend.com/wp-content/uploads/2016/06/placeholder-400x400.png'}
onClick={() => flipCard(card.id)}
/>
There is a Reaveal component in library. like below.
import React from 'react'
import { Image, Reveal } from 'semantic-ui-react'
const RevealExampleFade = () => (
<Reveal animated='fade'>
<Reveal.Content visible>
<Image src='/assets/images/wireframe/square-image.png' size='small' />
</Reveal.Content>
<Reveal.Content hidden>
<Image src='/assets/images/avatar/large/ade.jpg' size='small' />
</Reveal.Content>
</Reveal>
)
export default RevealExampleFade
but it does animations on hover. Is there a way to make it switch content on click? I'm not able to see any examples where we can.
You can make a Card become visible via the onClick event by conditionally rendering the Card component. It will end up looking something like this:
import React from 'react'
import { Image, Grid } from 'semantic-ui-react'
const FlipCard = (props) => {
const { id, flipped, cardImage } = props.card
const { hiddenImage, onCardFlip } = props
if(flipped){
//this image will be displayed once the card is clicked
return(
<Image width={200} src={cardImage} />
)
}
else{
//this image will be displayed if the card has not been clicked
return(
<Image id={id} onClick={onCardFlip} width={200} src={hiddenImage} />
)
}
}
class CardGame extends React.Component {
constructor(){
super();
this.state = {
cards : [
{
id: 0,
flipped: false,
cardImage: 'https://upload.wikimedia.org/wikipedia/commons/thumb/2/25/Playing_card_spade_A.svg/2000px-Playing_card_spade_A.svg.png',
},
{
id: 1,
flipped: false,
cardImage: 'http://vignette2.wikia.nocookie.net/yugioh/images/d/d4/BlueEyesWhiteDragon-DUSA-EN-UR-1E.png/revision/latest?cb=20170330172041',
},
{
id: 2,
flipped: false,
cardImage: 'https://www.palossports.com/imagez/15327_12.jpg',
},
],
hiddenImage: 'https://s-media-cache-ak0.pinimg.com/originals/6c/a0/16/6ca016115a894f69dea75cc80f95ad92.jpg',
}
}
handleCardFlip = (e, data) => {
const cards = this.state.cards
cards[e.target.id].flipped = true
this.setState({ cards })
}
render(){
const { hiddenImage, cards } = this.state
const mappedCards = cards.map( card => {
return(
<FlipCard key={card.id} hiddenImage={hiddenImage} card={card} onCardFlip={this.handleCardFlip} />
)
})
return(
<div>
{ mappedCards }
</div>
)
}
}
export default CardGame
I am new to react native,I have a block of code for a form in react, need to convert this into react native elements using the same let variable AddTodo
let AddTodo = ({ dispatch }) => {
let input
return (
<div>
<form onSubmit={e => {
e.preventDefault()
if (!input.value.trim()) {
return
}
dispatch(addTodo(input.value))
input.value = ''
}}>
<input ref={node => {
input = node
}} />
<button type="submit">
Add Todo
</button>
</form>
</div>
)
}
AddTodo = connect()(AddTodo)
Can anyone help me here? This is the source code
Here is simple code for react-native, that convert from your react code.
You can find more about react-native here.
in html we use for group other element so for react-native using
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
class AddTodo extends Component {
constructor(props) {
super(props);
this.state = {
todoText: ''
};
}
render() {
return (
<View>
<TextInput
onChangeText={(todoText) => this.setState({todoText})}
value={this.state.todoText}
/>
<TouchableHighlight onPress={() => {
if(this.state.todoText) {
this.props.addTodo(input.value);
this.setState({ todoText: '' })
}
}}>
<Text>Add Todo</Text>
</TouchableHighlight>
</View>
);
}
}
function mapStateToProps(state) {
return {};
}
function mapDispatchToProps(dispatch) {
return {
addTodo: bindActionCreators(addTodo, dispatch)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(AddTodo);
You can find react-native redux todo example here