How to Properly Import Function in a Reactjs File

How to properly import function in a ReactJS file

It looks like you have an extra bracket in there, also, the imported function will just be onSignUp not this.onSignUp.

import  onSignUp  from '../../functions/onsignup'

class ModalExample extends React.Component {

constructor(props) {
super(props);
this.onSignUp = onSignUp.bind(this);
}

render(){
return(...)
}
}

You should bind the function in the ctor or alternatively assign it in the class to onSignup like this:

import  onSignUp  from '../../functions/onsignup'

class ModalExample extends React.Component {

constructor(props) {
super(props);
}

onSignUp = onSignUp.bind(this);

render(){
return(...)
}
}

(I think)

How can I use a function from another file in react?

You can do something like:

function.js

const doSomething = function() {
let i = 0;
if (this === that) {
i = 0;
} else {
i = 1;
}

}

export default doSomething;

App.js (for example):

import doSomething from "./function";

class Example extends Component {
state = {
test
};
render() {
doSomething()
return (
<div>
<h1>{this.state.test.sample[i].name}</h1>
</div>
)

React router: How to import functions

You need to define welcome function as below:

export const Welcome = () => {return ()}

and then import it this way:

import { Welcome } from '../App.js'

How to properly import and test a function(s) within a named export react functional component?

randoColor lives only in the scope of the method ChatList, so it can't be accessed from the outside. Also it's better to access react components only thru the props.

Since the method doesn't use any of the ChatList props, I would recommend moving it outside of the method. Like:

const ChatList = ({ chats }) => { 
if (chats.length > 0) {
return <main></main
}
}
ChatList.randoColor = max => Math.floor(Math.random() * Math.floor(max))
export default ChatList

And that can be accessed like:

import ChatList from '../Components/ChatList'
ChatList.randoColor(230)

I would recommend moving that function somewhere else like creating a utils folder and have like a utils/colorUtils.js with this method and others that are related to color. And that leaves the component <ChatList /> more clean and the only way possible to change it is thru props or maybe Context.

Also I changed the export ChatList to export default ChatList, so that you can access it without the { }

Importing a function from a different file in React Native

you can't do that.

try this

exports.default = {
LoginScreen : ({ navigation }) => {
return (
<View>
<Text> This is a Login Screen </Text>
<Button
title="Go to Home"
onPress={() => navigation.navigate('Home')}
/>
</View>
)
},


HomeScreen : ({ navigation }) => {
return (
<View>
<Text> This is a Home Screen </Text>
</View>
)
}

}

this is a hint, not exact code.



Related Topics



Leave a reply



Submit