JBrowse 2 · React App examples

Add tracks programmatically

Add a track config at runtime with addTrackConf + showTrack.

Register additional tracks on a running view by calling addTrackConf and showTrack from an event handler — not during render:

state.jbrowse.addTrackConf({
  type: 'FeatureTrack',
  trackId: 'my_genes',
  name: 'My Genes',
  assemblyNames: ['hg38'],
  adapter: {
    type: 'Gff3TabixAdapter',
    uri: 'https://example.com/genes.gff.gz',
  },
})
state.session.views[0]?.showTrack('my_genes')

The slots available on a track config come from its config docs (e.g. FeatureTrack), and each adapter type has its own page too (e.g. Gff3TabixAdapter). To extend the app with new track types, adapters, or renderers rather than just adding tracks, see plugins.

Live demo

View source
import { useRef, useState } from 'react'

import { JBrowse } from '@jbrowse/react-app2'

import { volvoxConfig } from '../volvoxConfig.ts'

import type { ViewModel } from '@jbrowse/react-app2'

// a track config you want to add at runtime instead of up front (here pulled
// from the volvox config, but it could be any track config object)
const genesTrackConf = volvoxConfig.tracks.find(
  t => t.trackId === 'gff3tabix_genes',
)!

export default function AddTracksProgrammatically() {
  // ref to the live engine, for imperative control after launch
  const ref = useRef<ViewModel>(null)
  const [added, setAdded] = useState(false)

  function addTrack() {
    const state = ref.current
    if (state) {
      state.jbrowse.addTrackConf(genesTrackConf)
      state.session.views[0]?.showTrack('gff3tabix_genes')
      setAdded(true)
    }
  }

  return (
    <div>
      <button
        disabled={added}
        onClick={() => {
          addTrack()
        }}
      >
        {added ? 'Genes track added' : 'Add genes track'}
      </button>
      <JBrowse
        ref={ref}
        assemblies={volvoxConfig.assemblies}
        tracks={volvoxConfig.tracks.filter(
          t => t.trackId !== 'gff3tabix_genes',
        )}
        sessionName="Programmatic tracks"
        views={[
          {
            type: 'LinearGenomeView',
            init: { assembly: 'volvox', loc: 'ctgA:1..50000' },
          },
        ]}
      />
    </div>
  )
}