Bind Click Event in WebView Android React Native - react-native

I want to bind click event inside webview
Below is my code but its not working.
_renderContent() {
var s = '';
if(this.state.contents.length > 0) {
this.state.contents.map(( guid, i) => {
s += '<div style="font-size:48;padding-left:10px;"><button onClick = alert("hi");>try<button></div>';
});
return (
<WebView
source={ { html: s} }
scalesPageToFit={true}
startInLoadingState={false}
/>
);
}
}

What happens if you close your button tag properly and maybe wrap your alert('hi') in quotes?
<div style="font-size:48;padding-left:10px;"><button onClick="alert('hi')";>try</button></div>

Related

Add row in Material Table on button click from outside material table in react js

How to call add row functionality of the material table when clicking the button from outside of the material table
Add new row in the material table
Import import { forwardRef } from "react";
Call
const addActionRef = React.useRef();
Include this code in the place u want ur button. I am using material ui button here
<Button
color="primary"
variant="contained"
onClick={() => addActionRef.current.click()} //The line you need
>
Add new item
</Button>
and override the action in material table
components = {
{
Action: props => {
//If isn't the add action
if (typeof props.action === typeof Function || props.action.tooltip !== 'Add') {
return <MTableAction { ...props
}
/>
} else {
return <div ref = {
addActionRef
}
onClick = {
props.action.onClick
}
/>;
}
}
}
}
If u have any question please ask.
I have used here react js with material ui.
https://github.com/mbrn/material-table/issues/2133
This link might help u.... this is from where I got the answer

React Native is there an attribute equals to alt on image component

Coming from reactjs i was expecting "alt" attribute on the image component that will show text in case the image could not be loaded.
I read the documentation here and the closest thing I found is the on error event.
Is there an attribute equal to alt in React Native image component? And what is the easiest way to replace your image with a default text if i don't have the alt attribute?
You can make such a component yourself, it requires a very minimal amount of code. Here's a basic example:
export default class AccessibleImage extends Component {
state = {
error : false
};
_onImageLoadError = (event) => {
console.warn(event.nativeEvent.error);
this.setState({ error : true });
}
render() {
const { source, alt, style } = this.props;
const { error } = this.state;
if (error) {
return (
<Text>{alt}</Text>
);
}
return (
<Image
accessible
accessibilityLabel={alt}
source={source}
style={style}
onError={this._onImageLoadError} />
);
}
}
This will show the provided alt if there was an error loading the image and also use that text as the accessibilityLabel for screen readers which is closer to web behaviour.
A better answer than the previous if using React Native 0.68+ is to include the alt attribute on an <Image> Component like so
<Image
style={styles.yourImageStyles}
source={{
uri: 'https://reactnative.dev/img/tiny_logo.png',
}}
alt={'Alternate text that will be read be screen readers'}
/>
Chatgpt said:
let displayImage;
try {
displayImage = <Image source={require('./secondImage.png')} />;
} catch (error) {
displayImage = <Text>Second Image not available</Text>;
}
and to use the image/text:
{displayImage}

firestore document id will be undefined after I update array

I have this flatlist which receive data from firestore and send as props to projectsummery.js
const ProjectList =({projects})=> {
return(
<FlatList
data={projects}
renderItem={(project,index)=>{
return(
<ProjectSummery project={project} key={project.item.id}
//keyExtractor={(item, index) =>item.id}/>
)
} }
/>
)
}
Here I have a button which which sends document id which is something like this
{project.item.id} == CSmet3tRjpjDcJ437M78
ProjectSummery.js
const ProjectSummery =(props)=> {
const {project,auth}=props
return(
<>
<View >
<Text> {project.item.title} </Text>
<Text>likes { project.item.likes.length}</Text>
<Text>{project.item.id}</Text>//document id in in firestore
<View>
<Button title='like' onPress{()=>props.likesPosts(project.item.id)}/>
</View>
</View>
const mapDispatchToProps=(dispatch)=>{
return{
likePosts:(postId)=>dispatch(likePosts(postId))
}
}
When I try to update array in firebase the first time it work but the second time the document id will be undefined. I use React-Native. Thanks for help...
export const likePosts = (postId) => {
return (dispatch,getState,{getFirebase,getFirestore})=>{
const profile=getState().firebase.profile
const authId=getState().firebase.auth.uid
const firestore=getFirestore()
firestore.collection('projects').doc(postId).update({
//this postId will be be undefined in the 2nd time
likes:firestore.FieldValue.arrayUnion({
likedAt:new Date(),
likedBy:authId,
name: profile.firstName
})
})
}}
The fist update postId == CSmet3tRjpjDcJ437M78 in the 2nd time postId will be undefined
What's happening is that when you click a like button the first time, it's working as expected so it gets the proper postId and then continues with the process you have defined. However, when you try the 2nd time it fails to fetch the postId as it's already liked.
The idea is that you'll need to either define an if statement and specify what should happen if it's already clicked and it get's clicked again (possibly storing the postId somewhere the first time and using it from there), or make an initial check that returns a specific message to the user if it's already clicked.
The issue has nothing to do with Firestore itself but with the button and the states of liked/unliked.
Here is one nice interactive example on codepen.io of a proper way of building like buttons using react. React Like Button
HTML
<div id="example"></div>
CSS
.btn-primary {
background-color: #23aa4e;
border-color: #177d37;
}
#example {
margin: 3rem;
}
.customContainer {
border: 1px solid black;
}
JS
class LikeButton extends React.Component {
constructor() {
super();
this.state = {
liked: false
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({
liked: !this.state.liked
});
}
render() {
const text = this.state.liked ? 'liked' : 'haven\'t liked';
const label = this.state.liked ? 'Unlike' : 'Like'
return (
<div className="customContainer">
<button className="btn btn-primary" onClick={this.handleClick}>
{label}</button>
<p>
you {text} this. Click to toggle.
</p>
</div>
);
}
}
ReactDOM.render(
<LikeButton />,
document.getElementById('example')
)

How to use External web page in React Native View

I want to use external web page in my React Native App . I have button on my app and want to open external web page onPress button in my app not on browser.
I have tried WEBVIEW but not helped me.
now I have Tried this :
<HTMLView
value={this.props.html}
onLinkPress={(url) => alert('clicked link: ', url)}
/>
how can i do this ?
I have tried this and its working for me.
install react-native-custom-tabs using this command
npm install react-native-custom-tabs --save
and than link custom tabs package using
react-native link react-native-custom-tabs
and than call it
import {CustomTabs,ANIMATIONS_SLIDE,ANIMATIONS_FADE} from 'react-native-custom-tabs';
openCustomizedCustomTabs() {
this.openGoogle({
toolbarColor: '#607D8B',
enableUrlBarHiding: true,
showPageTitle: true,
enableDefaultShare: true,
animations: ANIMATIONS_SLIDE
});
}
errorOccur() {
this.openGoogle({
//toolbarColor: '607D8B', // <--- Invalid toolbar color.
enableUrlBarHiding: '#607D8B', // <-- Type Error.
})
}
openGoogle(option) {
CustomTabs.openURL('https://www.google.com', option).then((launched: boolean) => {
console.log(`Launched custom tabs: ${launched}`);
}).catch(err => {
console.error(err)
});
}
render(){
return <Button marginTop={10} onPress={() => this.openCustomizedCustomTabs()}>
Custom Tab
</Button>
}
and run app.
function renderNode(node, index, siblings, parent, defaultRenderer) {
if (node.name == 'iframe') {
const a = node.attribs;
const iframeHtml = `<iframe src="${a.src}"></iframe>`;
return (
<View key={index} style={{width: Number(a.width), height: Number(a.height)}}>
<WebView source={{html: iframeHtml}} />
</View>
);
}
}
class Page extends React.Component {
render() {
const htmlContent = `
<div>
<iframe src={this.props.utl} width="360" height="300" />
</div>
return (
<HTMLView value={htmlContent} renderNode={renderNode} />
);
}
}
then use it like:
<Page url="the url here..." />
React Native WebView Component has been Added in new Release to Documentation .
https://facebook.github.io/react-native/docs/webview.html
import React, { Component } from 'react';
import { WebView } from 'react-native';
class MyWeb extends Component {
render() {
return (
<WebView
source={{uri: 'https://github.com/facebook/react-native'}}
style={{marginTop: 20}}
/>
);
}
}

How to set state on child component?

I have a component that renders out a list of buttons, lets call this 'ButtonList'. When one of the buttons is clicked, the event is bubbled up like so:
<ButtonList onButtonPressed={(mins) => { console.log(mins); }} />
In response to this, I want to hide that ButtonList and show another component that is currently hidden. The ButtonList has some state such as "state { visible: true }" that I want to toggle that stops it rendering. How do I make a call to toggle the state of that ButtonList and then also call my other component in this view to also toggle its visible state to show?
Thanks.
swappingComponentsExample = () => {
return (
<View>
{this.state.showButtonList ? (
<ButtonList
onButtonPressed={mins => {
this.setState({showButtonList: false});
console.log(mins);
}}
/>
) : (
<OtherComponent />
)}
</View>
);
};
// Renders both components but passes style override to hide the object
// ButtonList/OtherComponent are not destroyed and recreated using this method
hidingExample = () => {
return (
<View>
<ButtonList
onButtonPressed={mins => {
this.setState({showButtonList: false});
console.log(mins);
}}
style={!this.state.showButtonList && {display: 'none'}}
/>
<OtherComponent
style={this.state.showButtonList && {display: 'none'}}
/>
</View>
);
};